我有一个包含%的字符串,我也想使用%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认为我试图在字符串中插入多个变量,但只包括一个.我该如何克服这个问题?谢谢!
您可以使用%此语法在字符串中使用a ,方法是将其转义为另一个%:
>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
295 次 |
| 最近记录: |