Pythonic
Pythonic

Reputation: 2131

How to remove specific characters in front of another specific character?

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

Answers (3)

Jean-François Fabre
Jean-François Fabre

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

Laurent LAPORTE
Laurent LAPORTE

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

gitaarik
gitaarik

Reputation: 46370

Why not just:

re.sub(' +\(', '(', my_string)

Upvotes: 4

Related Questions