2016-11-13 36 views
0

我刚开始Automate The Boring Stuff,我在第1章错误“无法将‘诠释’对象隐含STR”

myname = input() 
print ('It is nice to meet you,' + myname) 
lengthofname = len(myname) 
print ('your name is this many letters:' + lengthofname) 

我跑了这一点,它给了我Can't convert 'int' object to str implicitly。 我在第3行的推理是我想要将变量myname转换为整数,然后插入第4行。

为什么这会是一种错误的编码方式?

+2

请看http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly。在发布之前,请谷歌。 –

+0

使用逗号来分隔'print()'和'print()'中的参数会自动将它们转换为字符串 - 'print('你的名字是这么多字母:',lengthofname' – furas

回答

0

你的代码似乎是Python 3.x.以下是更正的代码;只需在print期间将lengthofname转换为字符串即可。

myname = input() 
print ('It is nice to meet you,' + myname) 
lengthofname = len(myname) 
print ('your name is this many letters:' + str(lengthofname)) 
2

当你有print ('your name is this many letters:' + lengthofname),蟒蛇正试图整数添加到字符串(这当然是不可能的)。

有3种方法可以解决此问题。

  1. print ('your name is this many letters:' + str(lengthofname))
  2. print ('your name is this many letters: ', lengthofname)
  3. print ('your name is this many letters: {}'.format(lengthofname))
2

你有问题,因为+可以两个数字相加或连接两个字符串 - 你有string + number所以你必须之前,你可以到数字转换为字符串连接两个字符串 - string + str(number)

print('your name is this many letters:' + str(lengthofname)) 

但是你可以运行print(),其中许多参数用逗号分隔 - 就像其他函数一样 - 然后Python会在print()显示它们之前自动将它们转换为字符串。

print('your name is this many letters:', lengthofname) 

您只记得print会在参数之间添加空格。
(你可以说“逗号增加空格”,但打印它。)

相关问题