Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的字计数器_Python - Fatal编程技术网

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"

我曾尝试用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")
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)))