Python Count the number of vowels in a string
In Python, we can count the number of vowels in a string by iterating through each character in the string and checking whether it is a vowel (a, e, i, o, u). The following is a simple example code.
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!"
print(f"The number of vowels is: {count_vowels(text)}")
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count
# Example string
text = "Hello, World!"
print(f"The number of vowels is: {count_vowels(text)}")
Code analysis:
vowels = "aeiouAEIOU": Defines a string containing all vowel letters, including both uppercase and lowercase.count = 0: Initializes a counter to record the number of vowels.for char in s:: Iterate through the stringsfor each character.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)}"): Callcount_vowelsthe function and print the result.
Output result:
元音字母的数量是: 3Other extensions
Python3 Examples