1

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?

Community
  • 1
  • 1
Pythonic
  • 2,091
  • 3
  • 21
  • 34

3 Answers3

4

Why not just:

re.sub(' +\(', '(', my_string)
gitaarik
  • 42,736
  • 12
  • 98
  • 105
3

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)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

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)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103