0

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":""}
martineau
  • 119,623
  • 25
  • 170
  • 301
Thirumal
  • 8,280
  • 11
  • 53
  • 103
  • 2
    You can use raw strings: `r"M L\\n\\nL\\n\\nS"` – Mark Apr 27 '22 at 00:47
  • the input I receive from JSON is `\\n` – Thirumal Apr 27 '22 at 00:47
  • 2
    The json you are receiving is a single backslash followed by an `n`. The backslash is escaped, otherwise it would be a newline character. In other words, your json does not have two backslashes, "\\" is a single character in the same way "\n" is a single character. – Mark Apr 27 '22 at 00:49

2 Answers2

1

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

PreciseMotion
  • 330
  • 1
  • 14
1

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 ".