Python在包含(%)的字符串中使用(%s)?

kro*_*761 2 python python-2.7

我有一个包含%的字符串,我也想使用%s用变量替换该字符串的一部分.就像是

name = 'john'
string = 'hello %s! You owe 10%.' % (name)
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我得到了

not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)

我很确定这意味着python认为我试图在字符串中插入多个变量,但只包括一个.我该如何克服这个问题?谢谢!

Max*_*ant 8

您可以使用%此语法在字符串中使用a ,方法是将其转义为另一个%:

>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
Run Code Online (Sandbox Code Playgroud)

更多关于:字符串格式化操作 - Python 2.x文档


正如@Burhan在我的帖子后添加的那样,你可以使用Python 3推荐format语法绕过这个问题:

>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
Run Code Online (Sandbox Code Playgroud)