Java和Python中字符串和数字连接的区别

2024-04-26 18:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Java之上学习Python,所以我对Python提供的字符串连接功能感到困惑。 在Python中,如果使用简单的加号(+)运算符连接字符串和数字,则会引发错误。 但是,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

Tags: 字符串inhellooutput数字javaoutsystem
2条回答

Java和Python是不同的语言。Java有一个String连接,它将把int提升为String。在Python中,你必须自己做。比如

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

提供输出:

>>> 25hello30
>>> hello1015

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

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

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

提供输出:

>>> 25hello30
>>> hello1015

相关问题 更多 >