寫一個 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-hant/n/127554.html