31

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 9

82

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')
1
  • 6
    Your last option reads beautifully, thanks very much - just what I'd expect from Python!
    – alexmuller
    Aug 10, 2011 at 9:08
11

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.
10

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'
>>>
1
  • Precisely what I was looking for. Clean and simple. +1 Nov 5, 2018 at 16:29
6

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)
5
>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'
3

You could use named parameters. See examples here

3
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)
1

have a look at Template Strings

0

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}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.