9
str = 'I love %s and %s, he loves %s and %s.' 

I want to use this format to display

I love apple and pitch, he loves apple and pitch.

Only add two variable please, but need a way to use it twice in one sentence.

user469652
  • 48,855
  • 59
  • 128
  • 165

2 Answers2

25

Use a dict:

>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
>>> s % {"x" : "apples", "y" : "oranges"}
'I love apples and oranges, he loves apples and oranges.'

Or use the newer format function, which was introduced in 2.6:

>>> s = 'I love {0} and {1}, she loves {0} and {1}'
>>> s.format("apples", "oranges")
'I love apples and oranges, she loves apples and oranges'

Note: Calling a variable str would mask the built-in function str([object]).

miku
  • 181,842
  • 47
  • 306
  • 310
  • Is there any reason why one should use `format` rather than a dictionary? Or is it just a matter of personal preference? – little-dude Jun 22 '15 at 09:50
  • 1
    I believe the `.format` [spec](https://docs.python.org/2/library/string.html#formatspec) just covers more cases. A similar question was asked here: http://stackoverflow.com/q/5082452/89391. My personal preference is to use `%` for brevity and performance and `.format`, if readability is improved. – miku Jun 22 '15 at 10:17
6
>>> str = 'I love %(1)s and %(2)s, he loves %(1)s and %(2)s.' % {"1" : "apple", "2" : "pitch"}
>>> str
'I love apple and pitch, he loves apple and pitch.'

Of course you can use other names besides '1' and '2'. :)

Ruel
  • 15,438
  • 7
  • 38
  • 49