Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete specific duplicated punctuation from string

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading