0

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)

1 Answer 1

2

You need to escape the backslash -

temp = r"abc\abc"
temp.replace('\\', 'backslash')
'abcbackslashabc'
Sign up to request clarification or add additional context in comments.

2 Comments

The important thing here is to not use r (raw string) for the single backslash, because r'\\' is a string with two backslashes. Yes, it's confusing.
I understand... \\ is like a shortcut or alias to \... and r'\\' is actually two backslashes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.