为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2023-10-18 22:04:34
print("This is a string" + 123)连接会引发错误,但使用逗号即可完成这项工作。
查看完整描述

6 回答

?
米脂

TA贡献1836条经验 获得超3个赞

正如您已经被告知的,您的代码会引发错误,因为您只能连接两个字符串。在您的情况下,串联的参数之一是整数。

print("This is a string" + str (123))

但你的问题更多的是“加号与逗号”。为什么人们应该+工作时使用,

嗯,对于参数来说确实如此print,但实际上在其他情况下您可能需要连接。例如在作业中

A = "This is a string" + str (123)

在这种情况下,使用逗号会导致不同的(并且可能是意外的)结果。它将生成一个元组而不是串联。


查看完整回答
反对 回复 2023-10-18
?
繁花如伊

TA贡献2012条经验 获得超12个赞

嘿,您正在尝试连接字符串和整数。它会抛出类型错误。你可以尝试类似的东西

print("This is a string"+str(123))

逗号 (,) 实际上并不是连接值,它只是以看起来像连接的方式打印它。另一方面,连接实际上会连接两个字符串。


查看完整回答
反对 回复 2023-10-18
?
噜噜哒

TA贡献1784条经验 获得超7个赞

这是一个案例print()。但是,如果您确实需要字符串,则可以使用连接:

x = "This is a string, "+str(123)

得到你" This is a string, 123"

你应该写

x = "This is a string", 123

你会得到元组("This is a string",123)。那不是字符串,而是完全不同的类型。


查看完整回答
反对 回复 2023-10-18
?
12345678_0001

TA贡献1802条经验 获得超5个赞

如果变量中有 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


查看完整回答
反对 回复 2023-10-18
?
绝地无双

TA贡献1946条经验 获得超4个赞

# 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!'


查看完整回答
反对 回复 2023-10-18
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

原因很简单,它123是一种int类型,而你不能concatenate int使用str类型。


>>> s = 123

>>> type(s)

<class 'int'>

>>>

>>> w = "Hello"+ s

Traceback (most recent call last):

  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'


查看完整回答
反对 回复 2023-10-18
  • 6 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信