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
  • 1,961
  • 3
  • 18
  • 34

3 Answers3

4

Why not just:

re.sub(' +\(', '(', my_string)
gitaarik
  • 36,986
  • 11
  • 91
  • 97
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
  • 131,796
  • 23
  • 122
  • 195
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
  • 20,141
  • 5
  • 53
  • 92