Reputation: 51
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
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.
string = r"10\S\12/L"
string = "10\S\\12/L"
Upvotes: 3
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:
'\\12'
r'\12'
Upvotes: 7