当逗号(,)完成这项工作时,在Python中使用连接(+)有什么意义?

print("This is a string" + 123)

连接会引发错误,但使用逗号即可完成这项工作。


一只斗牛犬
浏览 115回答 6
6回答

米脂

正如您已经被告知的,您的代码会引发错误,因为您只能连接两个字符串。在您的情况下,串联的参数之一是整数。print("This is a string" + str (123))但你的问题更多的是“加号与逗号”。为什么人们应该在+工作时使用,?嗯,对于参数来说确实如此print,但实际上在其他情况下您可能需要连接。例如在作业中A = "This is a string" + str (123)在这种情况下,使用逗号会导致不同的(并且可能是意外的)结果。它将生成一个元组而不是串联。

繁花如伊

嘿,您正在尝试连接字符串和整数。它会抛出类型错误。你可以尝试类似的东西print("This is a string"+str(123))逗号 (,) 实际上并不是连接值,它只是以看起来像连接的方式打印它。另一方面,连接实际上会连接两个字符串。

噜噜哒

这是一个案例print()。但是,如果您确实需要字符串,则可以使用连接:x = "This is a string, "+str(123)得到你" This is a string, 123"你应该写x = "This is a string", 123你会得到元组("This is a string",123)。那不是字符串,而是完全不同的类型。

12345678_0001

如果变量中有 int 值,则可以使用 f-string(格式字符串)将其打印出来。格式需要更多输入,例如print(("one text number {num1} and another text number {num2}").format(num1=variable1, num2=variable2)x = 123 print(("This is a string {x}").format(x=x))上面的代码输出:This is a string 123

绝地无双

# You can concatenate strings and int variables with a comma, however a comma will silently insert a space between the values, whereas '+' will not. Also '+' when used with mixed types will give unexpected results or just error altogether.>>> start = "Jaime Resendiz is">>> middle = 21>>> end = "years old!>>> print(start, middle, end)>>> 'Jaime Resendiz is 21 years old!'

慕无忌1623718

原因很简单,它123是一种int类型,而你不能concatenate int使用str类型。>>> s = 123>>> type(s)<class 'int'>>>>>>> w = "Hello"+ sTraceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: can only concatenate str (not "int") to str>>>>>>>>> w = "Hello" + str(s)>>>>>> w'Hello123'>>>您可以看到错误,因此您可以使用函数将s其值为字符串的变量转换为字符串。但是在这种情况下,您想将字符串与其他类型连接起来吗?我认为你应该使用123str()f-strings例子>>> boolean = True>>> fl = 1.2>>> integer = 100>>>>>> sentence = f"Hello variables! {boolean} {fl} {integer}">>> sentence'Hello variables! True 1.2 100'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python