Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
bjg90 Avatar asked May 18 '26 11:05

bjg90


2 Answers

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'
like image 107
Brad Solomon Avatar answered May 21 '26 00:05

Brad Solomon


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"
like image 36
Raiyan Chowdhury Avatar answered May 21 '26 00:05

Raiyan Chowdhury



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!