python - 如何创建不包含空格的字数?
问题描述
我是 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))
解决方案
将此代码用作改进
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
,并且尝试对其进行索引会导致错误
推荐阅读
- mongodb - 将数组与文档中的现有数组连接起来
- spring-cloud - 在 zipkin 中记录消息
- python - 为什么 Python 中协方差函数的输出相差太大?
- jvm - 使用 OpenJ9 的类数据共享时,应该对 JVM 内存的哪个区域影响最大
- google-analytics - 在 BigQuery 中为自定义维度复制 Google Analytics 所有会话
- php - iframe-curl 内容盗窃
- java - 有没有办法使用意图打开特定组(家庭应用程序、电话应用程序)的默认应用程序屏幕?
- php - 在 PHP 语句中更改文本框的值
- bash - 按下向上箭头并更改 bash 提示后,文本破碎
- php - 从 PHP SOAP 响应解析 XML 数据