首页 > 解决方案 > 修复python中的基本字数

问题描述

所以我的代码有问题,我的字数总是等于“4”,每当我输入不同数量的字时,这都是不准确的。

这是我的代码:

word=raw_input("Enter your string please: ")
count=0
for i in "word":
    count += 1
    if word == " ":
        print(count) 
print "Your word count:", count
print "Your character count:", (len(word))

样本输出:

Enter your string please: ched hcdbe checbj
Your word count: 4
Your character count: 17

我的字符数非常好,这只是我的字数。我很困惑我需要解决什么。帮助将不胜感激!

标签: pythonstringcountword-count

解决方案


调试

以下行无效,因为您正在迭代字符串 word 中的每个元素而不是用户输入:

for i in "word":

应该是

for i in word:

完全修复(使用两个单独的变量进行单词和字符计数):

word= input("Enter your string please: ")
charCount = 0
wordCount = 0
for i in word:
    charCount += 1
    if i == ' ':
        wordCount += 2
print("Your character count:", charCount)
print("Your word count:", wordCount)

现在,一种更短的方法

使用str.format()len()

word = input("Enter your string please: ")

print("Total words: {}".format(len(word.split())))
print("Total Characters: {}".format(len(word)))

输出

Enter your string please: hey, how're you?
Total words: 3
Total Characters: 16

推荐阅读