寫一個 Python 程序來計算一個字元串中的總字數,並給出一個實例。
計算字元串中總字數的 Python 程序示例 1
這個 python 程序允許用戶輸入一個字元串(或字元數組)。接下來,它使用 For 循環計算該字元串中出現的單詞總數。這裡,我們使用 Python For 循環來迭代字元串中的每個字元。在 For 循環中,我們使用 If 語句來檢查是否有空格。如果它找到了空白,那麼總字數就會增加。
# Python program to Count Total Number of Words in a String
str1 = input("Please Enter your Own String : ")
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
print("Total Number of Words in this String = ", total)
計算字元串字數的 Python 程序示例 2
這個 python 程序的一個字元串的總字數同上。然而,我們只是將換成了而環。
# Python program to Count Total Number of Words in a String
str1 = input("Please Enter your Own String : ")
total = 1
i = 0
while(i < len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
i = i + 1
print("Total Number of Words in this String = ", total)
Python 使用 while 循環輸出對字元串中的單詞進行計數
Please Enter your Own String : Tutorial Gateway
Total Number of Words in this String = 2
計算字元串總字數的 Python 程序示例 3
該 Python 計數字元串中的總字數與第一個示例相同。但是,這一次,我們使用了函數概念來分離 Python 邏輯。
# Python program to Count Total Number of Words in a String
def Count_Total_Words(str1):
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
return total
string = input("Please Enter your Own String : ")
leng = Count_Total_Words(string)
print("Total Number of Words in this String = ", leng)
Python 使用函數輸出對字元串中的單詞進行計數
Please Enter your Own String : Python Hello World Program
Total Number of Words in this String = 4
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/251875.html