Home > OS >  How to avoid double backslashes in string literals being replaced with single backslash?
How to avoid double backslashes in string literals being replaced with single backslash?

Time:04-27

Python string replaces double backslash with a single backslash? How avoid replace? I need to keep \\n as it is.

Code:

if __name__ == "__main__":
    str1 = '{"en":"M  L\\n\\nL\\n\\nS","fr":""}'
    print(str1)
    print("{}".format(str1))

Output:

 {"en":"M  L\n\nL\n\nS","fr":""}
 {"en":"M  L\n\nL\n\nS","fr":""}

Expected output:

 {"en":"M  L\\n\\nL\\n\\nS","fr":""}

CodePudding user response:

Use raw strings by inputting an r before the string:

r"M L\\n\\nL\\n\\nS"

This will ignore any and all escape characters.

Read more here: Raw Strings in Python

CodePudding user response:

If you want to tell python to not convert \\ to \ you can specify your string as raw string. This will auto escape \ so they will be seen as they are. A raw string is a string that no characters can be escaped in it. You can do this by putting a r char before the string starts:

r"M  L\\n\\nL\\n\\nS"

>>> "M  L\\\\n\\\\nL\\\\n\\\\nS"

So you can see that python automatically escaped all the \ characters so when you use this string it will interpret as "M L\\n\\nL\\n\\nS".

If you have a multi line string you can do this the same way:

a = r"""abcdefg\n\t\a
dygkcy\d\wscd"""

note: There is no difference for ' and ".

  • Related