I have this string s = "(0|\\ 33)[1-9]( *[0-9]{2}){4}"
. And I want to delete just the duplicated just one ' \ '
, like I want the rsult to look like (0|\ 33)[1-9]( *[0-9]{2}){4}
.
When I used this code, all the duplicated characters are removed:
result = "".join(dict.fromkeys(s))
.
But in my case I want just to remove the duplicated ' \ '
. Any help is highly appreciated
CodePudding user response:
The function you need is replace
s = "(0|\\ 33)[1-9]( *[0-9]{2}){4}"
result = s.replace("\\","")
EDIT
I see now that you want to remove just one \
and not both.
In order to do this you have to modify the call to replace
this way
result = s.replace("\","",1) # last argument is the number of occurrances to replace
or
result = s.replace("\\","\")
EDIT of the EDIT
Backslashes are special in Python.
I'm using Python 3.10.5. If I do
x = "ab\c"
y = "ab\\c"
print(len(x)==len(y))
I get a True
.
That's because backslashes are used to escape special characters, and that makes the backslash a special character :)
I suggest you to try a little bit with replace
until you get what you need.
CodePudding user response:
A solution using the re module:
import re
s = r"(0|\\ 33)[1-9]( *[0-9]{2}){4}"
s = re.sub(r"\\(?=\\)", "", s)
print(s)
I look for all backslashes, that are followed by another backslash and replace it with an empty sign.
Output: (0|\ 33)[1-9]( *[0-9]{2}){4}