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

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.

Use formatting strings:

>>> variable = """My name is {name} and it has been {name} since..."""
>>> n = "alex"
>>>
>>> variable.format(name=n)
'My name is alex and it has been alex since...'

The text within the {} can be a descriptor or an index value.

Another fancy trick is to use a dictionary to define multiple variables in combination with the ** operator.

>>> values = {"name": "alex", "color": "red"}
>>> """My name is {name} and my favorite color is {color}""".format(**values)
'My name is alex and my favorite color is red'
>>>

Use the new string.format:

name = 'Alex'
variable = """My name is {0} and it has been {0} since I was born.
          My parents decided to call me {0} because they thought {0} was a nice name.
          {0} is the same as {0}.""".format(name)

Use a dictionary instead.

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

Or format with explicit numbering.

var = '{0} {0} {0}'.format('look_at_meeee')

Well, or format with named parameters.

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')