bjg90
bjg90

Reputation: 51

Why does python interpret '\12' as '\n'

I have a string that contains the following sequence in it '10\S\12/L'

I want to split the string based on lines using .split('\n') however it causes the string to break on the '\12'. I found whenever a string contains this the interpreter prints the string with a line break.

Why is '\12' the same as '\n' and how can i prevent it?

Upvotes: 3

Views: 273

Answers (2)

Raiyan Chowdhury
Raiyan Chowdhury

Reputation: 311

As mentioned from comments, Python interprets the 12 as n as because 12 is its ASCII code. You have two ways of fixing this.

  1. Add "r" to the beginning of the string.
string = r"10\S\12/L"
  1. Escape each slash you want included in your string. So if you want "\12" literally, use:
string = "10\S\\12/L"

Upvotes: 3

Brad Solomon
Brad Solomon

Reputation: 40878

Because Python is interpreting that as the octal code for a newline, led off by that backslash escape and followed by 12.

You can see that in reverse:

>>> # Python 3.9 REPL
>>> oct(ord('\n'))
'0o12'

See the Python docs on String and Bytes Literals:

"\ooo denotes the [unicode] character with octal value ooo ... accepting up to 3 digits," but in this case, stops at those two.

If you want to include a literal backslash in your string, you can either:

  • escape it with another backslash: '\\12'
  • use a raw string literal prefixed with "r": r'\12'

Upvotes: 7

Related Questions