首页 > 解决方案 > Java 和 Python 中字符串和数字连接的区别

问题描述

我在 Java 之上学习 Python,所以我对 Python 提供的字符串连接功能感到困惑。在 Python 中,如果使用简单的 plus(+) 运算符连接字符串和数字,则会引发错误。然而,Java 中的相同内容会打印正确的输出并将字符串和数字连接起来或将它们相加。

为什么 Python 不支持以与 Java 相同的方式连接字符串和数字。

  1. 这有什么隐藏的优势吗?
  2. 我们如何在 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

标签: javapythonpython-3.x

解决方案


Java 和 Python 是不同的语言。Java 有一个String可以将 an “提升”intString. 在 Python 中,你必须自己做。喜欢,

print(str(10+15)+"hello"+str(30))
print("hello"+str(10)+str(15))

给出输出:

>>> 25hello30
>>> hello1015

推荐阅读