-1

I am new to regex. How can I remove the spaces in the beginning and the end in this context.

a = "( a is a b )"

I was trying

re.sub(r"\([(\s*\w+\s*)]*\)",r"",a)

But I managed to write some for the pattern but for the replacement I couldn't get any idea. I am not sure, if it is correct for the pattern as well. Need your kind support. Thanks for your help.

2 Answers2

1

You could do this with two substitutions. There may be a better way.

import re

a = "( a is a b )"

print(re.sub('\(\s+', '(', re.sub('\s+\)', ')', a)))

Output:

(a is a b)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1

I think using lookahead/lookbehind is a better way in your case. In this pattern, it is checking if there is parentheses before or after spaces. (You can read details here). You can also read explanations for this regex pattern here

pattern = r"\s(?=\))|(?<=\()\s"
s = 'a = ( a is b )'
result = re.sub(pattern, '', s)

Output:

a = (a is b)
Zorojuro
  • 71
  • 5