Replace '(a)' with '@‘within a python string

时间:2016-04-15 15:16:52

标签: python regex string replace

I am iterating through a list of email addresses and found that a number were entered incorrectly, i.e., (a) instead of @. So, I am trying to replace (a) with @. The best I got so far is:

x = 'asdf(a)asdf.com'
found = re.sub(r'\s(a)\s', '@', x.strip(), flags=re.IGNORECASE)
print(found)

However, this simply prints the original input:

asdf(a)asdf.com

I tried a number of regexes, but it won't work. Please help!

A note to all who suggested using the str.replace() method. Since (a) is part of string, I would have to read the entire document as a (list of) strings, and then iterate through it. I don't think this is an economical solution in terms of processing power used. Also, the questions specifically asked for a regex and not a string method. Thanks for taking the time to respond anyway!

4 个答案:

答案 0 :(得分:9)

This seems simple enough to use .replace()

>>> x = 'asdf(a)asdf.com'
>>> x.replace('(a)', '@')
'asdf@asdf.com'

答案 1 :(得分:4)

Use the inbuilt str.replace method.

a = 'asd(a)bcd.com`
b = a.replace('(a)','@')

答案 2 :(得分:1)

Try changing your pattern to:

re.sub(r'\(a\)', '@', x.strip(), flags=re.IGNORECASE)

But you shouldn't be spamming people in the first place ;)

答案 3 :(得分:1)

Python Code

x = 'asdf(a)asdf.com'
found = re.sub(r'\(a\)', '@', x.strip(), flags=re.IGNORECASE)
print(found)

Ideone Demo