Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to replace backslash in python3 string

I have a string

"abc INC\","None", "0", "test"

From this string I want to replace any occurrence of backslash when it appears before " with a pipe |. I wrote the following code but it actually takes out " and leaves the \ behind.

import re
str = "\"abc INC\\\",\"None\", \"0\", \"test\""
str = re.sub("(\\\")", "|", str)
print(str)

Output: |abc INC\|,|None|, |0|, |test|
Desired Output: "abc INC|","None", "0", "test"

Can someone point out what am I doing wrong?

like image 665
r0xette Avatar asked Jul 26 '26 08:07

r0xette


1 Answers

See Jamie Zawinksi's famous quote about regular expressions. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.

The actual content of string str (bad name for a variable, by the way, since there's a built-in type of that name) is

"abc INC\","None", "0", "test"

Why not just

str.replace('\\"', '|"')

which will do exactly what you want.

like image 90
holdenweb Avatar answered Jul 28 '26 00:07

holdenweb