I have been asked to use the % placeholder to write something in python. I don't know how to do it can you help.
1 Answers
The formatting you're looking to use is as follows:
Say you want to place two variables,
name = 'Randy'
age = 55
into a string. You would use the following syntax
"Howdy, %s. You are %s years old." % (name, age)
This will place your two variables within the string and return this:
"Howdy, Randy. You are 55 years old."
However, this formatting method has become outdated. Once strings require several parameters, it will quickly become less readable. Python now prefers that you use the following format:
"Howdy, {}. You are {} years old.".format(name, age)"
Which will also return
"Howdy, Randy. You are 55 years old."
There are also some neat tricks, like using dictionaries to store your variables and format the string from there, like such.
person = {'name': 'Randy', 'age':55}
"Howdy, {name}. You are {age} years old.".format(**person)
Which will return the same sentence as above, and is easily readable. It also tells the code user what variables are supposed to be placed where which helps in making sense of your code.
Hope this helped, good luck and happy coding!

- 165
- 1
- 11
-
This is really helpful. Thank you! – Nico May 15 '19 at 13:59
-
I'm glad it helped you out! If you want to click on the star left of my answer to mark this question as answered I'd really appreciate it! – BlorbieRandy May 16 '19 at 14:06