-2

For example:

a = (r'''\n1''')

b = (r'''
2''')

print(a)
print(b)

The output of this example is this:

\n1

2

Meaning that even if b is supposed to be a raw string, it does not seem to work like one, why is this?

I also checked:

if '\n' in b:
    print('yes')

The output of this is yes meaning that b is a string, and indeed has \n string inside of it.

Parsee
  • 71
  • 6
  • 1
    Why is this inconsistent? *Escape sequences* don't work, but an actual newline is not an escape sequence. – Martijn Pieters Nov 21 '15 at 17:45
  • Don't use a triple-quoted string when you don't want extra whitespace, tabs and newlines. – pythad Nov 21 '15 at 17:47
  • Can read more about that in the docs. https://docs.python.org/2/reference/lexical_analysis.html#string-literals and this SO answer http://stackoverflow.com/q/4415259/4099593 – Bhargav Rao Nov 21 '15 at 17:49
  • Your question is missing any counter example of what you expected to happen instead, or why you thought this was caused by the parentheses. – Martijn Pieters Nov 21 '15 at 17:50

1 Answers1

1

In the raw string syntax, escape sequences have no special meaning (apart from a backslash before a quote). The characters \ plus n form two characters in a raw string literal, unlike a regular string literal, where those two characters are replaced by a newline character.

An actual newline character, on the other hand, is not an escape sequence. It is just a newline character, and is included in the string as such.

Compare this to using 1 versus \x31; the latter is an escape sequence for the ASCII codepoint for the digit 1. In a regular string literal, both would give you the character 1, in a raw string literal, the escape sequence would not be interpreted:

>>> print('1\x31')
11
>>> print(r'1\x31')
1\x31

All this has nothing to do with parentheses. The parentheses do not alter the behaviour of a r'''...''' raw string. The exact same thing happens when you remove the parentheses:

>>> a = r'''\n1'''
>>> a
'\\n1'
>>> print(a)
\n1
>>> b = r'''
... 2'''
>>> b
'\n2'
>>> print(b)

2
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343