Using multiple arguments for string formatting in Python (e.g., '%s … %s')

后端 未结 8 2110
谎友^
谎友^ 2020-12-04 08:16

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 u

8条回答
  •  眼角桃花
    2020-12-04 08:43

    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'))
    

提交回复
热议问题