-2

I have been asked to use the % placeholder to write something in python. I don't know how to do it can you help.

Nico
  • 3
  • 2

1 Answers1

2

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!

BlorbieRandy
  • 165
  • 1
  • 11