【问题标题】:Difference in String and Number concatenation in Java and Python [duplicate]Java和Python中字符串和数字连接的区别[重复]
【发布时间】:2019-06-20 03:36:18
【问题描述】:

我在 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

【问题讨论】:

  • Python 在连接值时不会隐式调用 __str__。 Java uses a StringBuilder object 隐式避免创建临时字符串。它将为每个元素调用正确的重载,并将它们全部转换为字符串。

标签: java python python-3.x


【解决方案1】:

1)连接和添加两个不同类型的对象意味着猜测结果应该是哪种类型以及它们应该如何组合,这就是它在python中被排除的原因。语言做出选择。

2) 这个问题已经回答了here。你可以这样做:

print("{}hello{}".format(10+15,30))
print("hello{}{}".format(10,15))

给出输出:

>>> 25hello30
>>> hello1015

【讨论】:

    【解决方案2】:

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

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

    给出输出:

    >>> 25hello30
    >>> hello1015
    

    【讨论】:

    • 值得一提的是,Python中构建字符串的首选方式是扩展性更强的.format()方法。
    • @Selcuk 这是真的,但在 Java 中也是如此,System.out.printf("%dhello%d%n", 10+15, 30);System.out.printf("hello%d%d%n", 10, 15)
    最近更新 更多