Python Count the number of vowels in a string

Document 对象参考手册Python3 Examples

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)}")

Code analysis:

  1. vowels = "aeiouAEIOU": Defines a string containing all vowel letters, including both uppercase and lowercase.
  2. count = 0: Initializes a counter to record the number of vowels.
  3. for char in s:: Iterate through the stringsfor each character.
  4. if char in vowels:: Check whether the current character is a vowel.
  5. count += 1: If it is a vowel, increment the counter by 1.
  6. return count: Return the final number of vowels.
  7. text = "Hello, World!": Define an example string.
  8. print(f"元音字母的数量是: {count_vowels(text)}"): Callcount_vowelsthe function and print the result.

Output result:

元音字母的数量是: 3

Document 对象参考手册Python3 Examples

Other extensions