1. 程式人生 > >Python計算字串中單詞的個數

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)