Reputation: 2131
In the string:
my_string = 'log (x)'
I need to remove all spaces ' '
in front of left parentheses '('
This post suggests using:
re.sub(r'.*(', '(', my_string)
which is an overkill because it has the same effect as my_string[my_string.index('('):]
and removes also 'log'
Is there some regexpr magic to remove all spaces in front of another specific character?
Upvotes: 1
Views: 244
Reputation: 140286
use forward lookahead:
re.sub(r"\s+(?=\()","",my_string)
the entity between parentheses is not consumed (not replaced) thanks to ?=
operator, and \s+
matches any number of whitespace (tab, space, whatever).
And another possibility without regex:
"(".join([x.rstrip() for x in my_string.split("(")])
(split the string according to (
, then join it back with the same character applying a rstrip()
within a list comprehension)
Upvotes: 3
Reputation: 22992
You can use a lookahead assertion, see the regular expression syntax in the Python documentation.
import re
my_string = 'log (x)'
print(re.sub(r'\s+(?=\()', '', my_string))
# log(x)
Upvotes: 1