所以我试着把它放在VSCode:中
character_name = "Mike"
character_age = 50
is_male = False
print("He really liked the name " + character_name + ", ")
print("but didn't like being " + character_age + ".")
然而,我会得到这个错误消息回来:
TypeError:只能将str(而不是"int"(连接到str
有解决方法吗?还是我应该把数字放在引号之间?
或者,如果您使用Python 3.6+,您可以使用f-string,因此您的代码可以写成:
character_name = "Mike"
character_age = 50
is_male = False
print(f"He really liked the name {character_name}, ")
print(f"but didn't like being {character_age}.")
就我个人而言,我更喜欢这样做,因为它是一种较短的语法,并且它会自动将str()
应用于变量。
错误
你的错误不是变量定义,而是第5行
打印("但不喜欢"+character_age+"."(
让我们看看您的错误消息
TypeError:只能将str(而不是"int"(连接到str
这是一个TypeError,它是因为您不能使用"而引发的+"为了添加int和str类型错误";
原因
int(integer(是数字,str(string(是单词。现在,你的错误变得显而易见;添加一个单词和一个数字是没有意义的。
我们可以将两个整数或两个字符串加在一起+"运算符,它必须是相同的类型。
让我们看看这里:
word = "this is a string" # Making a string example
number = 5 # This is an example int
print(word + number)
及其输出
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
在这里,我们得到了相同的错误消息,因为我们试图添加一个int
和str
现在,让我们尝试一个不同的示例
print(5 + 5) # Adding two integers
print("Hello " + "World!") # Adding two strings
print(5 + "Hello!") # Adding a string and an integer
这个例子的输出
>>> print(5 + 5) # Adding two integers
10
>>> print("Hello " + "World!") # Adding two strings
Hello World!
>>> print(5 + "Hello!") # Adding a string and an integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
在这里,两个数字相加有效,字符串也是如此。但是,我们在最后一个中遇到了一个错误,添加了一个字符串和一个整数
正确
在这种情况下,我们可以完全避免使用整数,因为我们不打算将该变量添加到另一个整数中。
character_age = "50" # Now its a string
这是输出
>>> character_name = "Mike"
>>> character_age = "50"
>>> is_male = False
>>> print("He really liked the name " + character_name + ", ")
He really liked the name Mike,
>>> print("but didn't like being " + character_age + ".")
but didn't like being 50.
或者,如果我们需要使用整数,我们可以将其转换为字符串,同时添加
print("but didn't like being " + str(character_age) + "."). # This will not affect the variable, but it will return a string version of character_age
这具有相同的输出
另一个答案是在python 3.6+中使用f-string
>>> print("The restaurant received a {5} star rating")
The restaurant received a 5 star rating
你可以在这里阅读更多关于f-string的
结论
您需要将int值转换为字符串以便添加,或者首先使用字符串。f-strings
是一种很好的方法,无需字符串串联,语法也更简单。
只需使用str(character_age(将整数转换为字符串变量。
print("He really liked the name " + character_name + ", ")
print("but didn't like being " + str(character_age) + ".")
或者使用逗号连接
print("He really liked the name ", character_name, ", ", sep="")
print("but didn't like being ", character_age, ".", sep="")