Python计算字符串中单词的个数

str = input("请您输入一串字符串:")
str1 = str.strip() #去掉头尾空格
index = 0
count = 0
while index < len(str1):
    while str1[index] != " ": #有空格时结束当前循环
        index += 1
        if index == len(str1): #下标与字符串长度相等结束当前循环
            break
    count += 1 #计算单词的个数
    if index == len(str1): #下标与字符串长度相等结束当前循环
        break
    while str1[index] == " ": #单词之间多个空格时,下标加1
        index += 1
print("输入的字符串中一共有count = %d个单词" % count)

猜你喜欢

转载自blog.csdn.net/yihong_li/article/details/81126437