0

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?

3
  • 2
    What about string = string.replace("#{turns} ","") ? Commented Jan 27, 2017 at 16:01
  • Well it works except that the spaces do not disappear... Commented Jan 27, 2017 at 16:02
  • What's not working with what you have? Commented Jan 27, 2017 at 16:02

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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*')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.