0

I have a CSV file with some fields such as first_name, last_name, etc and a string as follows.

Hi {first_name} {last_name}, ...

Note that the keys can change but they will always be a subset of the fields in the CSV.

How can I use string formatting to replace the value in the string from CSV?

2
  • Can you give us some sample input and your expected output? I'm not really clear on what you're after as your question stands right now Commented Oct 9, 2019 at 13:37
  • Hi, checkout the answer by @rankie567 Commented Oct 9, 2019 at 13:59

2 Answers 2

1

You can do something like this:

input = 'Hi {first_name} {last_name}'
# Assuming you have a dict of your variables
data = {
    'first_name': 'John',
    'last_name': 'Doe',
}
output = input.format(**data) # Hi John Doe
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this will work! I didn't know you could use formatting this way by unpacking.
0

let's say that you import a dataframe with pandas form a csv file. This dataframe is called people:

people dataframe

and a string variable like this to loop string formatting over all dataframe rows:

'Hi {first_name} {last_name}'

you can use this:

 [string.format(first_name = row['first_name'], last_name = row['last_name']) for index,row in people.iterrows()]

code example

1 Comment

I can't do first_name=row['first_name'] because first_name can be anything else as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.