Skip to main content
 首页 » 编程设计

python之% 与 + 与 Python 中的字符串相关

2025年05月04日19shihaiming

这个:

hilarious = False 
joke_evaluation = "Isn't that joke so funny?! %r" 
 
print joke_evaluation % hilarious 

还有这个:

w = "This is the left side of..." e = "a string with a right side."

print w + e

似乎在做同样的事情。为什么我不能更改代码以读取:

print joke_evaluation + hilarious 

为什么这行不通?

请您参考如下方法:

%r 调用 repr(),它将 False (bool) 表示为 "False" (string ).

+ 只能用于连接一个字符串和其他字符串(否则你会得到一个TypeError: cannot concatenate 'str' and 'bool' objects)

您可以在连接之前将 False 转换为字符串:

>>> print "Isn't that joke so funny?!" + str(False) 

您还可以尝试新的字符串格式:

>>> print "Isn't that joke so funny?! {!r}".format(False) 
Isn't that joke so funny?! False