Skip to content
Advertisement

Replacing character in string doesn’t do anything

I have a list like this,

['Therefore', 'allowance' ,'(#)', 't(o)o', 'perfectly', 'gentleman', '(##)' ,'su(p)posing', 'man', 'his', 'now']

Expected output:

['Therefore', 'allowance' ,'(#)', 'too', 'perfectly', 'gentleman', '(##)' ,'supposing', 'man', 'his', 'now']

Removing the brackets is easy by using .replace(), but I don’t want to remove the brackets from strings (#) and (##).

my code:

ch = "()"

for w in li:
    if w in ["(#)", "(##)"]:
        print(w)

    else:
        for c in ch:
            w.replace(c, "")
        print(w)

but this doesn’t remove the brackets from the words.

Advertisement

Answer

You can use re.sub. In particular, note that it can take a function as repl parameter. The function takes a match object, and returns the desired replacement based on the information the match object has (e.g., m.group(1)).

import re

lst = ['Therefore', 'allowance', '(#)', 't(o)o', 'perfectly', 'gentleman', '(##)', 'su(p)posing', 'man', 'his', 'now']

def remove_paren(m):
    return m.group(0) if m.group(1) in ('#', '##') else m.group(1)

output = [re.sub(r"((.*?))", remove_paren, word) for word in lst]
print(output) # ['Therefore', 'allowance', '(#)', 'too', 'perfectly', 'gentleman', '(##)', 'supposing', 'man', 'his', 'now']
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement