Sudhanshu Mishra
Sudhanshu Mishra

Reputation: 2094

How to dynamically format a templated string in Python?

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

Answers (2)

Federico Cattai
Federico Cattai

Reputation: 106

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

Upvotes: 0

frankie567
frankie567

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

Related Questions