【问题标题】:Python string iteration: how to print any non-vowel chars first, then vowels last (via For loop)Python 字符串迭代:如何先打印任何非元音字符,然后再打印元音(通过 For 循环)
【发布时间】:2020-02-13 21:26:24
【问题描述】:

我需要先返回所有非元音字符,然后返回任何给定字符串中的元音 last。这是我到目前为止所拥有的,首先打印非元音,但之后不打印任何元音:

# Python 3
# Split a string: consonants/any-char (1st), then vowels (2nd)

def split_string():
    userInput = input("Type a word here: ")
    vowels = "aeiou"
    for i in userInput:
        if i not in vowels:
            print(i, end="")
            i += i
        # else:
        #     if i in vowels:
        #         print(i, end="")
        #         i = i+i
        # This part does not work, so I commented it out for now!
    return(userInput)
input = split_string()

回答!我只需要一个 not 嵌套在第一个循环内的第二个循环。

def split_string():
    userInput = input("Type a word here: ")
    vowels = "aeiou"
    for i in userInput:
        if i not in vowels:
            print(i, end="")
            i += i
    for i in userInput:
        if i in vowels:
            print(i, end="")
    return(userInput)

input = split_string()

【问题讨论】:

  • 你需要两个循环。一个用于非元音。一个用于元音。
  • 谢谢,@MateenUlhaq。第二个循环(元音)需要嵌套在第一个循环中,对吗?这就是我遇到的麻烦。
  • 不,它们应该是两个独立的循环
  • 谢谢!我只需在函数中添加第二个循环就可以让它工作! :)

标签: python python-3.x


【解决方案1】:

这是一个惯用的答案。

def group_vowels(word):
    vowels = [x for x in word if x in "aeiou"]
    non_vowels = [x for x in word if x not in "aeiou"]
    return vowels, non_vowels

word = input("Type a word here: ")
vowels, non_vowels = group_vowels(word)
print("".join(non_vowels))
print("".join(vowels))

注意:

  • group_vowels 返回元音列表和非元音列表。
  • 或者需要两个列表或两个循环来计算元音和非元音。 (在这种情况下,我使用 both 两个列表和两个循环,因为它看起来更漂亮。)
  • 函数内没有用户输入(这是更好的样式)。
  • 您可以使用join 将一系列字符连接成一个字符串。

【讨论】:

    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多