Py学习  »  Python

python正则表达式regex

Prathamesh Ramesh Patil • 5 年前 • 1787 次点击  

我想把字符串中的元音都去掉。 但是下面的代码不起作用。 相反,我需要把转义字符放在^ 即 obj=re.compile(r'[\^aeiouAEIOU]')

import re

def disemvowel(string):
    obj=re.compile(r'[^aeiouAEIOU]')   
    k=obj.sub('',string)
    return k

s='This website is for losers LOL!'  
print( disemvowel(s) )
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57337
 
1787 次点击  
文章 [ 3 ]  |  最新文章 5 年前
Amar Kumar
Reply   •   1 楼
Amar Kumar    5 年前

试试这个:

def rem_vowel(string):
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in string.lower():
        if x in vowels:
            string = string.replace(x, "")

    print(string)

string = "This website is for losers LOL!"
rem_vowel(string) 
Binh
Reply   •   2 楼
Binh    5 年前

'' ,因此,无需添加 ^ 里面 []

import re

def disemvowel(string):
    obj=re.compile(r'[aeiou]', re.I)   
    k=obj.sub('',string)
    return k

s='This website is for losers LOL!'  
print(disemvowel(s))
# Ths wbst s fr lsrs LL!
Tim Biegeleisen
Reply   •   3 楼
Tim Biegeleisen    5 年前

实际上你现在的角色类 [^aeiouAEIOU] 除了 元音。请尝试此版本:

s = "This website is for losers LOL!"
out = re.sub(r'[aeiou]', '', s, flags=re.IGNORECASE)
print(s + "\n" + out)

这张照片:

This website is for losers LOL!
Ths wbst s fr lsrs LL!