简体   繁体   中英

How to add a character in a string after each vowel using python 3

I'm trying to write a program that takes in a string(sentence) and after each vowel it adds a letter for example: "Jon" becomes "Jofon". I thought doing it with for loops maybe(certainly) there is a better way. Here it's what I tried so far:

sen="Jon"
newString=""


for letter in sen:
    if letter == "a" or letter == "e" or letter == "i" or letter == "o" \ 
    or letter == "u" or letter == "y":
        newString+=letter+"f"+letter


print(newString)

It seems to add the letter "f" only to vowels leaving consonants out giving me this result:

 ofo

Of course, since there's no fallback for when it's not a vowel... You need an else :

for letter in sen:
    if letter in "aeiouy":
        newString+=letter+"f"+letter
    else:
        newString+=letter

(doesn't handle the case where the letters are uppercased BTW)

But there are more efficient (and pythonic ways) of doing it. Concatenating strings is underperformant, and this kind of problem is better solved using comprehensions or regular expressions.

In one line, using ternary and list comprehension, passed to "".join :

newstring = "".join(["{0}f{0}".format(letter) if letter.lower() in "aeiouy" else letter for letter in sen])

Alternative with regular expressions, capturing the vowel as a group and using it twice to wrap the f char against recalled group ( \\1 ) using raw prefix or \\1 is interpreted as ASCII character \\x01 instead:

re.sub("([aeiouy])",r"\1f\1","Jon",flags=re.IGNORECASE)

that finds a vowel, and replaces it by this vowel + f + this vowel again.

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