編寫一個 Python 程序,用 For 循環和 ASCII 值計算字元串中的母音,並給出一個實例。
這個 python 程序允許用戶輸入一個字元串。接下來,它使用 For 循環計算該字元串中母音的總數。
這裡,我們使用 Python For 循環來迭代字元串中的每個字元。在 For Loop 中,我們使用 If 語句檢查字元是否為 A、E、I、O、u、A、E、I、O、u,如果為真,則增加母音值,否則跳過該字元
提示:請參考弦文章了解蟒弦的一切。
# Python Program to Count Vowels in a String
str1 = input("Please Enter Your Own String : ")
vowels = 0
for i in str1:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i == 'A'
or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowels = vowels + 1
print("Total Number of Vowels in this String = ", vowels)
在這個程序中,我們使用降低功能將字元串覆蓋為小寫。這樣,您只能在 If 語句中使用 a、e、I、o、u(避免大寫字母)。
# Python Program to Count Vowels in a String
str1 = input("Please Enter Your Own String : ")
vowels = 0
str1.lower()
for i in str1:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
vowels = vowels + 1
print("Total Number of Vowels in this String = ", vowels)
Python 統計字元串輸出中的母音
Please Enter Your Own String : Hello World
Total Number of Vowels in this String = 3
>>>
Please Enter Your Own String : Tutorial Gateway
Total Number of Vowels in this String = 7
這個 python 程序使用 ASCII 值來統計母音。建議大家參考 ASCII 表文章了解 ASCII 值。
# Python Program to Count Vowels in a String
str1 = input("Please Enter Your Own String : ")
vowels = 0
for i in str1:
if(ord(i) == 65 or ord(i) == 69 or ord(i) == 73
or ord(i) == 79 or ord(i) == 85
or ord(i) == 97 or ord(i) == 101 or ord(i) == 105
or ord(i) == 111 or ord(i) == 117):
vowels = vowels + 1
print("Total Number of Vowels in this String = ", vowels)
Python 統計字元串中的母音輸出
Please Enter Your Own String : Python Tutorial
Total Number of Vowels in this String = 5
>>>
Please Enter Your Own String : Tutorial Gateway
Total Number of Vowels in this String = 7
原創文章,作者:UGQVY,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126665.html