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

How to replace backslashes to a different character in a string Python

I want to know how to use Python’s str.replace() function (or similar) to replace Backslashes…

When i try to do it:

>>> temp = r"abc\abc"
>>> temp.replace(r'\'', 'backslash')
'abc\\abc' # For some reason, temp.replace() does not replace '\' with 'backslash' even when using raw variable
>>> temp.replace(r'\\', 'backslash') # Same result
'abc\\abc'

How do i fix this? And why? (Linux, Debian/Ubuntu, x86_x64 processor)

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 :

You need to escape the backslash –

temp = r"abc\abc"
temp.replace('\\', 'backslash')
'abcbackslashabc'
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