Using multiple arguments for string formatting in Python (e.g., '%s ... %s')
I have a string that looks like '%s in %s'
and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:
'%s in %s' % unicode(self.author), unicode(self.publication)
But this doesn't work so how does it look in Python?
Solution 1:
Mark Cidade's answer is right - you need to supply a tuple.
However from Python 2.6 onwards you can use format
instead of %
:
'{0} in {1}'.format(unicode(self.author,'utf-8'), unicode(self.publication,'utf-8'))
Usage of %
for formatting strings is no longer encouraged.
This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.
Solution 2:
If you're using more than one argument it has to be in a tuple (note the extra parentheses):
'%s in %s' % (unicode(self.author), unicode(self.publication))
As EOL points out, the unicode()
function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:
'%s in %s' % (unicode(self.author,'utf-8'), unicode(self.publication('utf-8')))
And as of Python 3.0, it's preferred to use the str.format()
syntax instead:
'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))