Reputation: 2094
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?
Upvotes: 0
Views: 108
Reputation: 106
let's say that you import a dataframe with pandas form a csv file. This dataframe is called people:
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()]
Upvotes: 0
Reputation: 1760
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
Upvotes: 1