10.Python中print函数中中逗号和加号的区别

先看看print中逗号和加号分别打印出来的效果..

这里以Python3为例

1
print("hello" + "world")
helloworld
1
print("hello", "world")
hello world

这里发现加号的作用是连接字符串 而逗号相当于用空格连接字符串。

尝试一下不同数据类型的操作..

1
print("hello" + 123)
TypeError: must be str, not int
1
print("hello", 123)
hello 123

这里发现加号在Str类型与Num类型相加的出现了类型错误 逗号连接正常并返回字符串结果。

总结:

加号 + :两边只能是相同数据类型,在Python中主要是运算符的存在,而字符串等类型相加只是Python中的内置方法。

逗号 , : 在这里逗号更多的代表用空格的连接。

原文地址:https://www.cnblogs.com/ubuntu1987/p/11510862.html