简体   繁体   中英

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)

You need to escape the backslash -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM