2017-06-21 107 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将成为一个字符串。