寫一個 Python 程序,使用 For 循環和 While 循環計算字元串中的總字元數,並給出一個實例。
計算字元串中的字元總數的 Python 程序示例 1
這個 python 程序允許用戶輸入一個字元串。接下來,它使用 For 循環計算該字元串中的字元總數。
這裡,我們使用 Python For 循環來迭代字元串中的每個字元。在 For 循環中,我們遞增每個字元的總值。
# Python Program to Count Total Characters in a String
str1 = input("Please Enter your Own String : ")
total = 0
for i in str1:
total = total + 1
print("Total Number of Characters in this String = ", total)
Python 程序計算字元串中的字元數示例 2
這個字元串字元程序和上面的例子一樣。然而,在這個 Python 代碼中,我們使用了帶有範圍的 For Loop 。
# Python Program to Count Total Characters in a String
str1 = input("Please Enter your Own String : ")
total = 0
for i in range(len(str1)):
total = total + 1
print("Total Number of Characters in this String = ", total)
Python 計數字元串輸出
Please Enter your Own String : Tutorial Gateway
Total Number of Characters in this String = 16
>>>
Please Enter your Own String : Python
Total Number of Characters in this String = 6
計算字元串中的字元數的 Python 程序示例 3
這個 python 程序對字元進行計數同上。然而,我們只是將 For 循環替換為 While 循環。
# Python Program to Count Total Characters in a String
str1 = input("Please Enter your Own String : ")
total = 0
i = 0
while(i < len(str1)):
total = total + 1
i = i + 1
print("Total Number of Characters in this String = ", total)
Please Enter your Own String : Python Programming
Total Number of Characters in this String = 18
原創文章,作者:KBPTS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127554.html