【发布时间】:2019-06-20 03:36:18
【问题描述】:
我在 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
【问题讨论】:
-
Python 在连接值时不会隐式调用
__str__。 Java uses a StringBuilder object 隐式避免创建临时字符串。它将为每个元素调用正确的重载,并将它们全部转换为字符串。
标签: java python python-3.x