您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python中的字符串替换元音?

Python中的字符串替换元音?

这是使用列表而不是生成器的版本:

def removeVowels(word):
    letters = []            # make an empty list to hold the non-vowels
    for char in word:       # for each character in the word
        if char.lower() not in 'aeIoU':    # if the letter is not a vowel
            letters.append(char)           # add it to the list of non-vowels
    return ''.join(letters) # join the list of non-vowels together into a string

您也可以像

''.join(char for char in word if char.lower() not in 'aeIoU')

这样做的作用相同,只是一次join需要找到一个非元音来制作新的字符串,而不是将它们添加到列表中然后在最后将它们连接起来。

如果您想加快速度,将值字符串设置为aset可以更快地查找其中的每个字符,并且也具有大写字母意味着您不必将每个字符都转换为小写。

''.join(char for char in word if char not in set('aeIoUAEIoU'))
python 2022/1/1 18:35:17 有386人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶