简体   繁体   中英

remove this unidentified character “\” from string python

I want to remove this string "\\". But i can't remove it because it's needed to do "\\t or \\n". Then i try this one """"\\"""". But the python still don't do anything. I think the binary is not get this string. This is the code

remove = string.replace(""""\"""", " ")

And I want to replace

"\workspace\file.txt" become "workspace file.txt"

Anyone have any idea? Thanks in advance

You're trying to replace a backslash, but since Python uses backslashes as escape characters, you actually have to escape the backslash itself.

remove = str.replace("\\", " ")

DEMO:

In [1]: r"\workspace\file.txt".replace("\\", " ")
Out[1]: ' workspace file.txt'

Note the leading space. You may want to call str.strip on the end result.

You have to escape the backslash, as it has special meaning in strings. Even in your original string, if you leave it like that, it'll come out...not as you expect:

"\workspace\file.txt" --> '\\workspace\x0cile.txt'

Here's something that will break the string up by a backslash, join them together with a space where the backslash was, and trim the whitespace before and after the string. It also contains the correctly escaped string you need.

" ".join("\\workspace\\file.txt".split("\\")).strip()

View this way you can archive this,

>>> str = r"\workspace\file.txt"
>>> str.replace("\\", " ").strip()
'workspace file.txt'
>>> 

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