sarabc
sarabc

Reputation: 1

Remove #{word} from a string using regex (python)

I'm not familiar with regex, and it would be great to have some help.

I have a string: string = "You get #{turns} guesses." and I would like to remove #{turns} in order to have string = "You get guesses."

I've tried it with:

string = re.sub(re.compile('#{.*?}'),"",string)

Any suggestions?

Upvotes: 0

Views: 5807

Answers (2)

Mohammad Yusuf
Mohammad Yusuf

Reputation: 17074

For this specific question you can also do it like so:

import re

string = "You get #{turns} guesses."
re.sub(r'#\S+ ', r'', string)

Output:

'You get guesses.'

Regex:

'#\S+ ' Match # and match as many non space characters and a single space.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476750

Your code works, except that it does not remove a sufficient amount of spaces and that compilation is rather useless if you only use it once:

>>> string = "You get #{turns} guesses."
>>> string = re.sub(re.compile('#{.*?}'),"",string)
>>> string
'You get  guesses.'

So you probably want to compile the regex once, and then use it, and you better alter it to - for instance - remove tailing spaces:

rgx = re.compile('#{.*?}\s*')
string = rgx.sub('',string)

Note the \s* which will match with an arbitrary amount of spaces after the tag, and thus remove these as well:

>>> string = "You get #{turns} guesses."
>>> rgx = re.compile('#{.*?}\s*')
>>> string = rgx.sub('',string)
>>> string
'You get guesses.'

In case it is one word between the curly brackets ({}), you better use \w to exclude spaces:

rgx = re.compile('#{\w*}\s*')

Upvotes: 1

Related Questions