简体   繁体   English

如何使用python 3在每个元音后在字符串中添加一个字符

[英]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".我正在尝试编写一个接收字符串(句子)的程序,并在每个元音之后添加一个字母,例如:“Jon”变成“Jofon”。 I thought doing it with for loops maybe(certainly) there is a better way.我认为用 for 循环做这件事也许(当然)有更好的方法。 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:它似乎只将字母“f”添加到元音中,而将辅音去掉,结果如下:

 ofo

Of course, since there's no fallback for when it's not a vowel... You need an else :当然,因为当它不是元音时没有后备......你需要一个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) (不处理字母大写的情况 BTW)

But there are more efficient (and pythonic ways) of doing it.但是有更有效的(和 pythonic 方式)这样做。 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 :在一行中,使用三元和列表"".join ,传递给"".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:作为正则表达式的替代方案,将元音作为一个组捕获并使用它两次将f字符与使用原始前缀的调用组 ( \\1 ) 包装起来,或者\\1被解释为 ASCII 字符\\x01代替:

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

that finds a vowel, and replaces it by this vowel + f + this vowel again.找到一个元音,并再次用这个元音 + f + 这个元音替换它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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