python - 为什么我们必须在 python 中写 print('you are ' + str(32) + ' Years old' 什么时候
问题描述
为什么我们必须print('you are ' + str(32) + ' Years old')
在 python 中编写,而我们只能编写print('you are 32 Years old')
将整数添加到字符串并且它们都工作得很好
解决方案
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
>>>
推荐阅读
- autodesk-forge - 从 Forge 加载大模型
- android - 关闭应用程序几分钟后未调用android onLocationChanged方法
- sql - SQL-server 中的隐式缺失值到显式缺失值
- html - 尝试使用带有画廊的元素解决 CSS :nth-child 公式
- vsto - VSTO 插件安装程序 - 询问一些用户信息
- node.js - Node.js 从 html 获取值并使用 req.body。
- java - 如何从 Python 客户端订阅 websocket 用户队列?
- alfresco - BPMN 中的决策任务和业务任务有什么区别?如何使用 alfresco 实现决策任务?
- java - 百里香弹簧MVC
- jhipster - JHipster Gateway UI 不是从可执行战争开始的