%与Python中的字符串相关?

2024-07-06 23:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是:

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

为什么这样不行?你知道吗


Tags: ofthefalsesothatisthisleft
3条回答

这就是让我困惑的地方:

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

print joke_evaluation % hilarious

我希望它看起来像这样:

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

print joke_evaluation 

我想它在我看来只是有点古怪。你知道吗

这是类型转换问题。在Python中尝试连接到字符串时,只能连接其他字符串。您正试图将布尔值连接到字符串,这是不受支持的操作。你知道吗

你能做到的

print w + str(e) 

这将是功能性的。你知道吗

%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

相关问题 更多 >