Python 程序:统计字符串中的元音字母

编写一个 Python 程序,使用 For 循环和 ASCII 值,通过实际示例来统计字符串中的元音字母。

Python 程序:统计字符串中的元音字母示例

这个 Python 程序允许用户输入一个字符串。接下来,它使用 For 循环统计此字符串中元音字母的总数。

在这里,我们使用 Python For 循环来遍历字符串中的每个字符。在 For 循环中,我们使用 If 语句来检查该字符是否为 a、e、i、o、u、A、E、I、O、U。如果为真,则增加元音字母的计数,否则跳过该字符。

提示:请参考字符串文章,以了解 Python 字符串的所有内容。

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)
Python Program to Count Vowels in a String 1

Python 程序:统计字符串中的元音字母示例 2

在此程序中,我们使用 lower 函数将字符串转换为小写。这样,您就可以只在 If 语句中使用 a、e、i、o、u(避免大写字母)。

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)

统计字符串中元音字母的总数输出。

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

程序:统计字符串中元音字母总数的示例 3

这个程序使用 ASCII 值来计算元音字母。我建议您参考 ASCII 表文章来理解 ASCII 值。

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)

统计字符串中元音字母数量的输出。

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