Home > Blockchain >  Removing Spaces in text inside parentheses: Python
Removing Spaces in text inside parentheses: Python

Time:07-26

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.

CodePudding user response:

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)

CodePudding user response:

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)
  • Related