Python输入一串字符串,输出字符串单词的个数

南楼画角 提交于 2019-11-28 12:11:45
str = input("请您输入一串字符串:")
str1 = str.strip() # 去掉字符串前后空格
index = 0
count = 0
while index < len(str1):
    while str1[index] != " ": # 当不是空格是,下标加1
        index += 1
        if index == len(str1): # 当下标大小跟字符串长度一样时结束当前循环
            break
    count += 1  # 遇到空格加1
    if index == len(str1): # 当下标大小跟字符串长度一样时结束当前循环
        break
    while str1[index] == " ": # 当有两个空格时,下标加1,防止以一个空格算一个单词
        index += 1
print("输入的字符串中一共有count = %d个单词" % count)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!