Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字符串迭代:如何首先打印任何非元音字符,然后最后打印元音字符(通过For循环)_Python_Python 3.x - Fatal编程技术网

Python字符串迭代:如何首先打印任何非元音字符,然后最后打印元音字符(通过For循环)

Python字符串迭代:如何首先打印任何非元音字符,然后最后打印元音字符(通过For循环),python,python-3.x,Python,Python 3.x,我需要首先返回所有非元音字符,然后返回任何给定字符串中的元音最后一个。这就是我到目前为止所做的,首先打印非元音,但之后不打印任何元音: # 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

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

# 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()
回答!我只需要一个不嵌套在第一个循环中的第二个循环

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()

这里有一个惯用的答案

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_元音
    返回元音列表和非元音列表
  • 计算元音和非_元音需要两个列表或两个循环。(在本例中,我使用两个列表和两个循环,因为它看起来更漂亮。)
  • 函数中没有用户输入(这是更好的样式)
  • 您可以使用
    join
    将字符列表连接到一个字符串中

您需要两个环路。一个用于非元音。一个是元音。谢谢,@MateenUlhaq。第二个循环(对于元音)需要嵌套在第一个循环中,对吗?这就是我遇到的麻烦。不,他们应该是两个分开的回路谢谢!我只需在函数中添加第二个循环就可以使其正常工作!:)