python中的字计数器
我曾尝试用python创建一个单词计数器,但我的代码无法运行python中的字计数器,python,Python,我曾尝试用python创建一个单词计数器,但我的代码无法运行 word = input("Enter word or sentence") input("Your word/ sentence has"+ len(word) + " letters") 你能帮我解决这个问题吗 目前的结果是 TypeError: Can't convert "int" object into str implicity 您有一个错误: word = input("Enter word or sentence"
word = input("Enter word or sentence")
input("Your word/ sentence has"+ len(word) + " letters")
你能帮我解决这个问题吗
目前的结果是
TypeError: Can't convert "int" object into str implicity
您有一个错误:
word = input("Enter word or sentence")
print("Your word/ sentence has"+ str(len(word)) + " letters")
或:
input
接受字符串输入。如果要打印,必须使用print
len
返回一个整数值Str
将其转换为字符串
word = input("Enter word or sentence")
print("Your word/ sentence has"+ str(len(word)) + " letters")
您可以尝试以下代码:
word = input("Enter word or sentence")
input("Your word/ sentence has"+ str(len(word)) + " letters")
这里,我使用的是str(len(word))
而不是len(word)
。因为len(word)
返回一个数字,它是一个int
对象
你在做str\u object+int\u object
,Python不明白你真正想做什么
让我们看看:
>>> len('foobar')
6
>>> type(len('foobar'))
<class 'int'>
>>> len('foobar') + 'foobar'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
您也可以使用而不是两个+
。它可以自动将所有对象转换为str
,而且比您的代码可读性更好
所以只要使用:
word = input("Enter word or sentence")
input("Your word/ sentence has {} letters".format(len(word)))
str(len(word))
。因为len(word)
返回一个数字,它是一个int
对象。你在做str\u object+int\u object
,Python不明白你真正想做什么。因此,您必须将int\u对象
(由len(word)
返回)转换为str
对象使用str()
函数。谢谢!当我键入input(len(word))时,它确实起作用,您是否只想打印结果,而不是使用另一个input()
?如果是这样,你应该使用print(“你的单词/句子有”+str(len(word))+“字母”)
而不是input()
函数。我不喜欢使用print,因为程序一回答问题就会关闭。我在一个cmd.exe样式的程序中运行它。在这个程序中,如果我使用input(),那么我可以在我的时间内调用每一行。当我使用print()时,它会打印消息并尝试关闭程序。除了他们应该使用print
打印,而不是input
@khelwood:哦,是的。我不知道OP为什么在这里使用input()
,但这不是问题所在,我会发表评论而不是编辑我的答案。
>>> str(len('foobar'))
'6'
>>> type(str(len('foobar')))
<class 'str'>
>>> str(len('foobar')) + 'foobar'
'6foobar'
word = input("Enter word or sentence")
input("Your word/ sentence has {} letters".format(len(word)))