简体   繁体   English

在字符串中打印元音和元音计数

[英]Printing the vowels and the vowel count in a string

I will have to define a function that takes a person's full name and finds the total number of vowels in that input.我将必须定义一个 function来获取一个人的全名并在该输入中找到元音的总数。 And I need to output every vowel including the total number of vowels found.我需要 output 每个元音,包括找到的元音总数。 If the name does not contain any vowel then my function should print “No vowels in the name.”.如果名称不包含任何元音,那么我的 function 应该打印“名称中没有元音。”。 Two sample inputs and their corresponding outputs are given below:下面给出了两个示例输入及其相应的输出:

Sample input:样本输入:
(Steve Jobs) (史蒂夫·乔布斯)

(XYZ) (XYZ)

Sample Output:样品 Output:

Vowels: e, e, o.元音:e、e、o。 Total number of vowels: 3元音总数:3

No vowels in the name!名字中没有元音!

I know it is quite a simple program, but I am facing some difficulties in printing an output as shown in the Sample Output.我知道这是一个非常简单的程序,但我在打印 output 时遇到了一些困难,如示例 Output 所示。 Here's my incomplete code:这是我的不完整代码:

def vowels(full_name):
    
    for i in full_name:
        count = 0
        if i == 'a' or i == 'A' or i == 'e' or i == 'E' or i == 'i' or i =='I' or i == 'o' or i == 'O' or i == 'u' or i == 'U':
            count += 1
            print(i, end= ',')
            
    print('Total number of vowels: ', count)

How can I write a clean program to get the expected output?如何编写一个干净的程序来获得预期的 output? I'm really lost at this point在这一点上我真的迷路了

Some things that may be helpful: As the comments have already pointed out, your long chain of or s can be shortened by using in to check for substring membership:一些可能有帮助的事情:正如评论已经指出的那样,可以通过使用in检查 substring 成员资格来缩短or的长链:

>>> "a" in "AEIOUaeiou"
True
>>> "b" in "AEIOUaeiou"
False
>>> 

You can use filter to create a collection of vowels - only retaining those characters which are vowels:您可以使用filter创建元音集合 - 仅保留那些元音字符:

def is_vowel(char):
    return char in "AEIOUaeiou"

vowels = list(filter(is_vowel, "Bill Gates"))
print(vowels)

Output: Output:

['i', 'a', 'e']
>>> 

You know that if vowels is empty, you can print "No vowels in the name!"你知道如果vowels是空的,你可以打印"No vowels in the name!" . . If it's not empty, you can print your other message, and use str.join on vowels to print the vowels, seperated by commas:如果它不为空,您可以打印您的其他消息,并使用str.join on vowels打印元音,用逗号分隔:

print(", ".join(vowels))

Output: Output:

i, a, e
>>> 

The number of vowels found is just the length of vowels .找到的元音数就是vowels的长度。

vowels = "aeiou"

def is_vowel(char):
   return char in vowels

def count_vowels(word):
    vowels = [char for char in word if is_vowel(char.lower())]
    return len(vowels)

print('Total number of vowels:', count_vowels("Steve Jobs"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM