Remove the square brackets; you do not match the character class:
item = re.sub(r" \(\w+\)", "", item)
Demo:
>>> items = ["x (LOC)", "ds ds (32C)", "d'ds ds (LeC)", "ds-d da(LOQ)", "12345 (deC)"] >>> for item in items: ... print re.sub(r" \(\w+\)", "", item) ... x ds ds d'ds ds ds-d da(LOQ) 12345
One, but the last example does not have a space before the opening bracket ( ( ) and therefore does not match. You can make the space optional if you need this template too:
item = re.sub(r" ?\(\w+\)", "", item)
Perhaps something that is not a closing bracket will work for you:
item = re.sub(r" ?\([^)]+\)", "", item)
This corresponds to a wider range of characters than just \w .
In a regular expression, square brackets [...] denote a character class; character set for a single match. The class [ \(w+\)] means: matches a single character if it matches a set that includes a space, an opening bracket, all characters of the class \w , + plus or closing parentheses.
source share