【问题标题】:Find and print vowels from a string using a while loop使用 while 循环从字符串中查找和打印元音
【发布时间】:2020-12-23 03:59:05
【问题描述】:

学习作业(使用python 3):

对于一项学习作业,我需要编写一个程序来打印字符串中所有元音的索引,最好使用“while-loop”。 到目前为止,我已经设法设计了一个“for-loop”来完成工作,但我肯定需要一些关于“while-loop”的帮助

for循环解决方案:

string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""

for i in string:
    if i in vowels:
        indices += i
print( indices )

while循环解决方案:

string = input( "Typ in a string: " )
vowels = "a", "e", "i", "o", "u"
indices = ""

while i < len( string ):
    <code>
    i += 1
print( indices )

使用 'index()''find()' 在这里有用吗?

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    试试这个:

       string = input( "Typ in a string: " )
        vowels = ["a", "e", "i", "o", "u"]
    
    
    
    
            higher_bound=1
            lower_bound=0
    
            while lower_bound<higher_bound:
                convert_str=list(string)
                find_vowel=list(set(vowels).intersection(convert_str))
                print("Vowels in {} are {}".format(string,"".join(find_vowel)))
    
                lower_bound+=1
    

    您也可以将higher_bound 设置为len(string),然后它将打印结果与字符串的len 一样多。

    由于这是您的学习作业,您应该自己查看和练习,而不是复制粘贴。以下是解决方案的附加信息:

    在数学中,两个集合 A 和 B 的交集 A ∩ B 是集合 包含 A 中也属于 B 的所有元素(或 等价地,B 的所有元素也属于 A),但不属于其他元素 元素。有关本文中使用的符号的说明,请参阅 到数学符号表中。

    在python中:

    intersection()在Python中的语法是:

    A.intersection(*other_sets)

    A = {2, 3, 5, 4}
    B = {2, 5, 100}
    C = {2, 3, 8, 9, 10}
    
    print(B.intersection(A))
    print(B.intersection(C))
    print(A.intersection(C))
    print(C.intersection(A, B))
    

    【讨论】:

    • 谢谢保罗!真正有趣的解决方案也是如此,但我还没有那么先进。会到达那里,但也许不是今天;-)
    【解决方案2】:

    您可以通过 string[x]! 获取字符串索引 x 处的字符!

    i = 0 # initialise i to 0 here first!
    while i < len( string ):
        if string[i] in vowels:
            indices += str(i)
        i += 1
    print( indices )
    

    但是,将indices 设置为str 真的合适吗?我不这么认为,因为索引之间没有分隔符。字符串"12" 表示索引 1 和 2 处有 2 个元音,还是表示索引 12 处有一个元音?您可以尝试使用列表来存储索引:

    indices = []
    

    您可以通过以下方式添加i

    indices.append(i)
    

    顺便说一句,您的 for 循环解决方案将打印元音字符,而不是索引。

    如果不想使用列表,也可以在每个索引后面加一个空格。

    indices += str(I) + " "
    

    【讨论】:

    • 谢谢扫地机!困难在于我还没有学会使用列表,接下来的两章是元组和列表。我真的仍然很难仅使用我们迄今为止学到的“工具”来发挥创造力(这些包括:表达式、变量、条件、迭代、函数和当前章节的“字符串”)但我确实理解你的解释,谢谢你的帮助!
    • @GJ01 我编辑了答案。 解决这个问题的方法。
    • 太棒了!太感谢了! :-) 你对“元音”和“索引”也是正确的,但我不知道如何返回索引。
    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2021-12-19
    • 1970-01-01
    • 2019-03-01
    • 2016-01-15
    • 2012-03-09
    相关资源
    最近更新 更多