简体   繁体   中英

Python string iteration: how to print any non-vowel chars first, then vowels last (via For loop)

I need to return all non-vowel characters first, then vowels last from any given string. This is what I have so far, which is printing non-vowels first, but not printing any vowels after:

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

Answered! I simply needed a second loop that is not nested inside the first loop.

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

Here's an idiomatic answer.

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

Notice:

  • group_vowels returns a list of vowels and a list of non-vowels.
  • Either two lists or two loops are needed to compute the vowels and non_vowels. (In this case, I use both two lists and two loops because it looks prettier.)
  • No user input within a function (it's better style).
  • You can use join to concatenate together a list of characters into a single string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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