python - 在python中的字符串中的任何元音之前或之后立即删除 "y"

标签 python python-3.x string

我想删除字符串中的元音,为简单起见,我在下面的代码中只包含了小写字母

for x in "aeiou":
  st = st.replace(i,"")
  return st

这工作正常,但是我想知道如何处理我还想在包含元音的字符串中删除 y 的场景,如果它在左侧或右侧有任何元音 例如,在“may”上运行函数后,它应该返回“m”,类似于“mystery”到“mystry”。

最佳答案

这可能是一项家庭作业,但实际上最简单(虽然不一定是最快的)是使用正则表达式:

import re
p = re.compile(r'(?i)y?[aeiou]y?')

p.sub('', 'may')
# 'm'

p.sub('', 'mystery')
# 'mystry'

使用纯 python,您可以列出您的字符串,遍历每个字符,相应地删除字符(是的,您已经这样做了,因此您需要使用 if 语句修改现有代码以解决“y”的情况), 然后重新加入。这是一个例子。

def remove_vowels_with_y(string):
    # Cache vowel set for better lookup performance.
    v = set('aeiouAEIOU')
    # Listify your string. This is because strings are immutable.
    chars = list(string) + [''] # Sentinel character.
    # Initialization.
    filtered = []
    prev_is_vowel = False
    for i, c in enumerate(chars[:-1]): 
        # Add elements to `filtered` if conditions are met.
        if not (c in v or (c in 'yY' and (prev_is_vowel or chars[i+1] in v))):
            filtered.append(c)
        prev_is_vowel = c in v

    # Join filtered list and return result.    
    return ''.join(filtered)

remove_vowels_with_y('may')
# 'm'

remove_vowels_with_y('mystery')
# 'mystry'

关于python - 在python中的字符串中的任何元音之前或之后立即删除 "y",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837966/

相关文章:

python - Pandas /Python/Dropna : Renaming header column names after a dropna takes place with intention to import to MySQL

Python:使用 ascii 码打印

c - 将数据存储在程序中而不是外部文件中

java - 将表示 <img> 标签的字符串部分收集到 Java 8 中的列表中

python - Python 中高效的 CSV 阅读包?

python - 是否可以在 Pygame 中更改 Sprite 颜色?

javascript - AJAX django 获取请求

python - 将图像划分为网格(比如 3x3)并提取每个网格区域的像素值

python - 我想查找列表的总计,但出现错误

c# - 如何根据数字在 C# 中的值设置不同的格式?