6 回答

TA貢獻1836條經(jīng)驗 獲得超3個贊
正如您已經(jīng)被告知的,您的代碼會引發(fā)錯誤,因為您只能連接兩個字符串。在您的情況下,串聯(lián)的參數(shù)之一是整數(shù)。
print("This is a string" + str (123))
但你的問題更多的是“加號與逗號”。為什么人們應(yīng)該在+
工作時使用,
?
嗯,對于參數(shù)來說確實如此print
,但實際上在其他情況下您可能需要連接。例如在作業(yè)中
A = "This is a string" + str (123)
在這種情況下,使用逗號會導(dǎo)致不同的(并且可能是意外的)結(jié)果。它將生成一個元組而不是串聯(lián)。

TA貢獻2012條經(jīng)驗 獲得超12個贊
嘿,您正在嘗試連接字符串和整數(shù)。它會拋出類型錯誤。你可以嘗試類似的東西
print("This is a string"+str(123))
逗號 (,) 實際上并不是連接值,它只是以看起來像連接的方式打印它。另一方面,連接實際上會連接兩個字符串。

TA貢獻1784條經(jīng)驗 獲得超7個贊
這是一個案例print()
。但是,如果您確實需要字符串,則可以使用連接:
x = "This is a string, "+str(123)
得到你" This is a string, 123"
你應(yīng)該寫
x = "This is a string", 123
你會得到元組("This is a string",123)
。那不是字符串,而是完全不同的類型。

TA貢獻1802條經(jīng)驗 獲得超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

TA貢獻1946條經(jīng)驗 獲得超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!'

TA貢獻1744條經(jīng)驗 獲得超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'
>>>
您可以看到錯誤,因此您可以使用函數(shù)將s其值為字符串的變量轉(zhuǎn)換為字符串。但是在這種情況下,您想將字符串與其他類型連接起來嗎?我認為你應(yīng)該使用123str()f-strings
例子
>>> boolean = True
>>> fl = 1.2
>>> integer = 100
>>>
>>> sentence = f"Hello variables! {boolean} {fl} {integer}"
>>> sentence
'Hello variables! True 1.2 100'
添加回答
舉報