For example, if I have a base string "Hello <Name>, nice to meet you" and I want to personalize it for two or more people, with their own variable names, eg.
greeting_matt = "Hello Matt, nice to meet you"
greeting_henry = "Hello Henry, nice to meet you"
How do I do it in a single line, without code repetition?
CodePudding user response:
# Frist create a template
template = "Hello {name} with age {age}, nice to meet you"
# fill the placeholders
print(template.format(name="Matt", age=40))
print(template.format(name="Henry", age=42))
output:
Hello Matt with age 40, nice to meet you
Hello Henry with age 42, nice to meet you
CodePudding user response:
You can use str.format method; it formats the specified value and insert them inside the string's placeholder {}.
greeting = lambda name: "Hello {}, nice to meet you".format(name)
Output:
>>> greeting_matt = greeting('Matt')
'Hello Matt, nice to meet you'
>>> greeting_henry = greeting('Henry')
'Hello Henry, nice to meet you'
