用Python计算并显示字符串中的元音

给定一个字符串,让我们分析多少个字符是元音。

带套

我们首先找出所有单个和唯一字符,然后测试它们是否在表示元音的字符串中存在。

示例

stringA = "Nhooo is best"

print("Given String: \n",stringA)

vowels = "AaEeIiOoUu"

# Get vowels

res = set([each for each in stringA if each in vowels])

print("The vlowels present in the string:\n ",res)

输出结果

运行上面的代码给我们以下结果-

Given String:

Nhooo is best

The vlowels present in the string:

{'e', 'i', 'a', 'o', 'u'}

与fromkeys

通过将其视为字典,此功能可以从字符串中提取元音。

示例

stringA = "Nhooo is best"

#ignore cases

stringA = stringA.casefold()

vowels = "aeiou"

def vowel_count(string, vowels):

   # Take dictionary key as a vowel

   count = {}.fromkeys(vowels, 0)

   # To count the vowels

   for v in string:

      if v in count:

   # Increasing count for each occurence

      count[v] += 1

   return count

print("Given String: \n", stringA)

print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels))

输出结果

运行上面的代码给我们以下结果-

Given String:

nhooo is best

The count of vlowels in the string:

{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}

以上是 用Python计算并显示字符串中的元音 的全部内容, 来源链接: utcz.com/z/331427.html

回到顶部