首页 > 解决方案 > 为什么我们必须在 python 中写 print('you are ' + str(32) + ' Years old' 什么时候

问题描述

为什么我们必须print('you are ' + str(32) + ' Years old')在 python 中编写,而我们只能编写print('you are 32 Years old')将整数添加到字符串并且它们都工作得很好

标签: python

解决方案


print('you are 32 Years old')是的,如果我们希望它始终打印该常量行,我们可以像在 python 中一样编码。

当必须从变量中获取 32 时,如果我们确定变量类型是字符串,我们可以在没有 str() 转换的情况下使用。例如 :print('you are ' +x+ ' years old')

当我们不知道变量类型将始终为字符串时,我们需要将其显式转换为字符串,print('you are' +str(x)+ 'years old') .

没有那个str(x),当这个 x 是一个整数时,python 会给出这个错误:

>>> x = 32
>>> type(x)
<type 'int'>
>>> print ("you are "+ x + " years old")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> x = "32"
>>> type(x)
<type 'str'>
>>> print ("you are "+ x + " years old")
you are 32 years old
>>>

推荐阅读