首页 > 解决方案 > 如何创建不包含空格的字数?

问题描述

我是 python 的初学者,我的任务是创建一个接受字符串作为参数并返回字符串中单词数的函数。

我在分配空格和空白字符串时遇到问题。我觉得我错过了一些东西,但对于遗漏了什么或我搞砸了什么有点迷茫。我们也不能使用拆分。

任何指导或帮助将不胜感激

这是我到目前为止所拥有的:

def word_count(str):
count = 1
for i in str:
    if (i == ' '):
       count += 1                    
print (count)        

word_count('hello') --> 输出 = 1(到目前为止正确)

word_count('你好吗?') --> Output = 3 (也是正确的/至少我在找什么)

word_count('这个字符串有很宽的空格') --> Output = 7 (应该是 5...)

word_count(' ') --> Output = 2 (应该是''。我认为它在做count(1+1))

标签: pythonpython-3.x

解决方案


将此代码用作改进

def word_count(str):
    count = 1
    for i in str:
        if (i == ' '):
           count += 1
    if str[0] == ' ':
        count -= 1
    if str[-1] == ' ':
        count -= 1
    print (count)

您的错误是因为您的计数空间是从开头开始还是出现在结尾。请注意,您不能传递空字符串"",因为它被评估为NONE,并且尝试对其进行索引会导致错误


推荐阅读