Home > database >  Capturing a string without escape sequence
Capturing a string without escape sequence

Time:09-15

So I'm setting out on my coding journey by completing hackerrank problems, and I'm stuck in a step. I will not explain the problem, but will only try to explain the step I'm stuck in.

So I have a list of strings, all of them except for the last one have the "\r" escape sequence, as a string.

I try to remove the \r manually using re but fail to do so. Please help me out!

Here is the code:

`l = ['S;V;iPad\r', 'C;M;mouse pad\r', 'C;C;code swarm\r', 'S;C;OrangeHighlighter']
 pattern= re.compile("""\\[r]""")
 l_new = [pattern.match(i,'') for i in l] `

CodePudding user response:

What you're looking for is the re.sub() method:

import re

l = ['S;V;iPad\r', 'C;M;mouse pad\r', 'C;C;code swarm\r', 'S;C;OrangeHighlighter']
l_new = [re.sub(r'\r', '', i) for i in l]
print(l_new)

This will remove all occurrences of the \r escape sequence.

CodePudding user response:

I'd suggest not using the re module, and instead using the more pythonic approach of using [i.replace('\r','')for i in l].

  • Related