Home > OS >  Given a line in Python, how would I remove periods ONLY between brackets?
Given a line in Python, how would I remove periods ONLY between brackets?

Time:09-21

I read through a file that has lines that look like this:

 line='User . . has a {pass.word} but . it is {wro.ng}.' 

I want to remove the period, only between brackets what I need is:

 User . .  has a {password} but . it is {wrong}. 

So I read through the file and run re.sub trying to remove the periods just between brackets, not the others but all I'm able to do is to removing all the periods or removing nothing.

Someone give me a heads up please ?

Thanks in advance,

CodePudding user response:

We can try using re.sub here with a callback function:

line = "User . . has a {pass.word} but . it is {wro.ng}."
output = re.sub(r'\{.*?\}', lambda m: m.group().replace('.', ''), line)
print(output)  # User . . has a {password} but . it is {wrong}.

CodePudding user response:

Without lamba, you can use the pypi regex module and a quantifier in the positive lookarounds and sub with an empty string.

The [^{}] is a negated character class that matches any char except the curly's.

(?<={[^{}]*)\.(?=[^{}]*})

Regex demo

CodePudding user response:

Looking at an answer to another similar question, I adapted it for this line and it does not use lambda , not that I'm against lambda but I was also curious for an answer without lambda:

line= 'User . . has a ${pass.word} but . it is ${wro.ng}.'

  • actually this will be used in Python string templates so there is a dollar before the brackets, I didn't mention earlier as it was not relevant to question

re.sub(r"\.(?=[^}{]*\})", "", line)

Which gives:

'User . . has a ${password} but . it is ${wrong}.'

  • Related