简体   繁体   中英

(Python) Print all '\' escape characters

I have several strings with \\ in it. I try to not using escape characters by using the replace function like that:

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

It does not work.

When I use string.replace("\\n", "\\\\n") for \\n directly it works. Is there an easy working solution for that?

Important to note that replace does not act on the variable but rather returns a copy with the replacement applied See the docs :

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

print(this)
>"string\\string"

If you want the original string to be replaced,

this = this.replace("\\", "")

However, to convert \\n -> n would require that you think differently about this. ie replace('\\n', 'n') , as \\n is a single character.

You can try this:

def test():
    foo = r"this is a \\ and this is a \ "
    foo = foo.replace("\\" , r'\\') # added the r to ignore string escapes as escapes

    print(foo)

test()

output:

this is a \\\\ and this is a \\

使用原始字符串

r"This \ string \ includes '\'s"

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