user15930270
user15930270

Reputation:

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)

Upvotes: 0

Views: 125

Answers (1)

Czakky
Czakky

Reputation: 38

You need to escape the backslash -

temp = r"abc\abc"
temp.replace('\\', 'backslash')
'abcbackslashabc'

Upvotes: 2

Related Questions