Python Count the Vowels in a String
In Python, we can count the vowels in a string by iterating over each character and checking whether it is a vowel (a, e, i, o, u). Here is a simple example.
Example
def
count_vowels
(
s
)
:
vowels
=
"aeiouAEIOU"
count
=
0
for
char
in
s:
if
char
in
vowels:
count +
=
1
return
count
Example string
text
=
"Hello, World!"
(
f
"The number of vowels is: {count_vowels(text)}"
)
Code analysis:
vowels = "aeiouAEIOU": Define a string containing all vowels, both uppercase and lowercase.count = 0: Initialize a counter to record the number of vowels.for char in s:: Iterate over each character in the strings.if char in vowels:: Check whether the current character is a vowel.count += 1: If it is a vowel, increment the counter by 1.return count: Return the final number of vowels.text = "Hello, World!": Define an example string.print(f"元音字母的数量是: {count_vowels(text)}"): Callingcount_vowelsfunction and print the result.
Output result:
元音字母的数量是: 3
Python3 Examples