java - Java 和 Python 中字符串和数字连接的区别
问题描述
我在 Java 之上学习 Python,所以我对 Python 提供的字符串连接功能感到困惑。在 Python 中,如果使用简单的 plus(+) 运算符连接字符串和数字,则会引发错误。然而,Java 中的相同内容会打印正确的输出并将字符串和数字连接起来或将它们相加。
为什么 Python 不支持以与 Java 相同的方式连接字符串和数字。
- 这有什么隐藏的优势吗?
- 我们如何在 Python 中实现串联的东西
####################In Java########################33
System.out.println(10+15+"hello"+30) will give output 25hello30
System.out.println("hello"+10+15) will give output hello1015
#########In Python#########################
print(10+15+"hello"+30) will give error: unsupported operand type(s) for
+: 'int' and 'str'
print("hello"+10+15) can ony concatenate str(not "int") to str
解决方案
Java 和 Python 是不同的语言。Java 有一个String
可以将 an “提升”int
为String
. 在 Python 中,你必须自己做。喜欢,
print(str(10+15)+"hello"+str(30))
print("hello"+str(10)+str(15))
给出输出:
>>> 25hello30
>>> hello1015
推荐阅读
- python - 人脸编码的形状不同
- typescript - 无法在 ECS 计划任务 (aws-cdk) 中使用现有日志组
- r - 对使用仅应用于数字列的 mutate 和 rollmean 函数在 R 中有效地创建新列感到困惑
- python - 避免包重新上传到 PyPI
- react-native - 检测 react-router-native 中的路由变化
- python - 应用引用多列的 groupby 的最快最有效方法
- python - 每当我在“基本”环境中启动 Anaconda Prompt 时,有关 VSINSTALLDIR 和 vs2019 的长错误消息
- postgresql - TypeORM - 从现有实体生成迁移
- node.js - NodeJS - 如果请求来自特定的 URL 或主机,则表示接受请求
- apache-spark - 如何在 Spark 中从多个不同格式的文件创建一个 DataFrame?