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?
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:
'\\12'r'\12'As mentioned from comments, Python interprets the 12 as n as because 12 is its ASCII code. You have two ways of fixing this.
string = r"10\S\12/L"
string = "10\S\\12/L"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With