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