你经常需要在消息中使用变量的值
age=25
message="I'm"+age+"years old"
print(message)
>>>
Traceback (most recent call last):
File "str.py", line 2, in <module>
message="I'm"+age+"years old"
TypeError: can only concatenate str (not "int") to str
------------------
(program exited with code: 1)
Press return to continue
在此示例中,Python发现你使用了一个值为整数(int)的变量,但他不知道这个变量表示的是数值25,还是字符2和3。
为此应该调用函数str(),让Python将非字符串表示为字符串。
age=25
message="I'm"+" "+str(age)+" "+"years old"
print(message)
>>>
I'm 25 years old
------------------
(program exited with code: 0)
Press return to continue