0

In the REPL, I get the following output for 2 different scenarios

1st Scenario

>>> 'This is a \" and a \' in a string'

'This is a " and a ' in a string'

2nd Scenario

>>> a = 'This is a \" and a \' in a string'
>>> print(a)

This is a " and a ' in a string

In scenario 1, the second backslash is printed even though it is used as an escape character, but in scenario 2, it escapes. I was wondering why it happens so in scenario 1

Master_Roshy
  • 1,245
  • 3
  • 12
  • 19
  • 1
    The automatic printing of expression values in the REPL uses the `repr()` of the value, rather than the `str()` (as this is generally more detailed). To exactly duplicate scenario 1, scenario 2 would need to use `print(repr(a))`. – jasonharper Jun 10 '22 at 02:54

1 Answers1

0

Scenario 1 is treated as a text literal where the single quotes are part of the string. Scenario 2 assigns the value inside the two outermost quotes as the text value, so that both of those quotes are treated not as part of the text, but as delimiters.

To achieve the same result as scenario 1 in scenario 2, you would need to add escaped quotes at the appropriate positions, like so:

a = '\'This is a \" and a \' in a string\''
print(a)
shree.pat18
  • 21,449
  • 3
  • 43
  • 63
  • I was wondering why in scenario 1, the 2nd backslash appeared even though it is used as an escape character – Master_Roshy Jun 10 '22 at 02:55
  • When you're directly keying in text at the REPL input, each character is treated as a literal. See [this](https://stackoverflow.com/questions/35631884/why-does-the-python-interpreter-use-repr-to-print-expressions) for more info. – shree.pat18 Jun 10 '22 at 03:01