Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python about multiple %s in a string

Tags:

python

string

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.

like image 901
user469652 Avatar asked Dec 14 '10 01:12

user469652


1 Answers

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]).

like image 180
miku Avatar answered Sep 25 '22 20:09

miku