Output formatting in Python: replacing several %s with the same variable

Viewed 61504

I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:

variable = """My name is %s and it has been %s since I was born.
              My parents decided to call me %s because they thought %s was a nice name.
              %s is the same as %s.""" % (name, name, name, name, name, name)

There are little snippets that look like this all over the script, and I was wondering whether there's a simpler (more Pythonic?) way to write this code. I've found one instance of this that replaces the same variable about 30 times, and it just feels ugly.

Is the only way around the (in my opinion) ugliness to split it up into lots of little bits?

variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)
9 Answers

Python 3.6 has introduced a simpler way to format strings. You can get details about it in PEP 498

>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'

It also support runtime evaluation

>>>f"{2 * 30}"
'60'

It supports dictionary operation too

>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
 The comedian is Tom, aged 30.

If you are using Python 3, than you can also leverage, f-strings

myname = "Test"
sample_string = "Hi my name is {name}".format(name=myname)

to

sample_string = f"Hi my name is {myname}"
Related