2017-06-21 103 views
-6

我正在學習python,並且在這裏遇到了一些新問題。任何人都可以解釋這個Python代碼內部發生了什麼。字符串串聯失敗

>>> s="sam" 
>>> s +="dam" 
>>> s 
'samdam' 
>>> d +=s 
>>> d 
'msamdam' 
>>> f = f+s 

Traceback (most recent call last): 
    File "<pyshell#129>", line 1, in <module> 
    f = f+s 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 
>>> f +=s 

Traceback (most recent call last): 
    File "<pyshell#130>", line 1, in <module> 
    f +=s 
TypeError: unsupported operand type(s) for +=: 'int' and 'str' 
+2

代碼中的f是什麼? – HH1

+2

你能更新你的代碼以包含d和f的instanciations嗎? – Fabien

回答

0

fintegersstring。你不能連接數字和字符串。

你可以把它這樣做的工作:

x = str(f) + s 

這將f轉換爲字符串,然後用s串聯。例如,如果f123,x將是123msamdam

1

我可以假設變量f是整數類型,s是字符串。你不能以這種方式連接整數和字符串。如果你想這樣做,它應該是這樣的:

str(f) + s 
0

看來,f是這裏的一個整數,所以也許你可以使用:

f = str(f) + s 

這樣,F將成爲一個字符串。