It occurred to me that all the other answers are operating under the assumption that you wish to remove the @...
substring and maintain a separation of ' '
between different words (or sets of characters other than ' '
), as evidenced by your code. However, the question does not otherwise explicity point this as the objective. And, since there could potentially be a situation when (don't ask me) this behaviour isn't the correct one, here we go!
Edit: Readable and flexible now (vs old code-golfy versions)
My original post was a bit silly in that the code really wasn't meant for production; it worked, but that was it. This now accomplishes three types of substring substractions effortlessly, although perhaps it could be done better with regular expressions (not too experienced there).
text = "hey @foo say hi to @bar"
Regular version with only a single ' '
to separate the remaining words
newText = ''.join(
text[i] if text.rfind('@', 0, i+2) <= text.rfind(' ', 0, i+1) else
'' for i in xrange(len(text)))
>>> 'hey say hi to'
Removes only the specified substring (without removing any other whitespace)
newText = ''.join(
text[i] if text.rfind('@', 0, i+1) <= text.rfind(' ', 0, i+1) else
'' for i in xrange(len(text)))
>>> 'hey say hi to '
Transforms the substring into whitespace
newText = ''.join(
text[i] if text.rfind('@', 0, i+1) <= text.rfind(' ', 0, i+1) else
' ' for i in xrange(len(text)))
>>> 'hey say hi to '
Hope this helps, somehow!