2

I want to output

XYZ's "ABC"

I tried the following 3 statements in Python IDLE.

  • 1st and 2nd statement output a \ before '.
  • 3rd statement with print function doesn't output \ before '.

Being new to Python, I wanted to understand why \ is output before ' in the 1st and 2nd statements.

>>> "XYZ\'s \"ABC\""
'XYZ\'s "ABC"'

>>> "XYZ's \"ABC\""
'XYZ\'s "ABC"'

>>> print("XYZ\'s \"ABC\"")
XYZ's "ABC"
S.B
  • 13,077
  • 10
  • 22
  • 49
Rohit
  • 23
  • 5
  • This has been explained here: https://stackoverflow.com/questions/24052654/python-string-adding-backslash-before-single-quotes – mkrieger1 Mar 21 '22 at 13:09
  • 1
    Being new to python, i just wanted to understand the difference. I have edited the question and @SorousH answer explains it well. – Rohit Mar 21 '22 at 13:09

2 Answers2

4

Here are my observations when you call repr() on a string: (It's the same in IDLE, REPL, etc)

  • If you print a string(a normal string without single or double quote) with repr() it adds a single quote around it. (note: when you hit enter on REPL the repr() gets called not __str__ which is called by print function.)

  • If the word has either ' or " : First, there is no backslash in the output. The output is gonna be surrounded by " if the word has ' and ' if the word has ".

  • If the word has both ' and ": The output is gonna be surrounded by single quote. The ' is gonna get escaped with backslash but the " is not escaped.

Examples:

def print_it(s):
    print(repr(s))
    print("-----------------------------------")

print_it('Soroush')
print_it("Soroush")

print_it('Soroush"s book')
print_it("Soroush's book")

print_it('Soroush"s book and Soroush\' pen')
print_it("Soroush's book and Soroush\" pen")

output:

'Soroush'
-----------------------------------
'Soroush'
-----------------------------------
'Soroush"s book'
-----------------------------------
"Soroush's book"
-----------------------------------
'Soroush"s book and Soroush\' pen'
-----------------------------------
'Soroush\'s book and Soroush" pen'
-----------------------------------

So with that being said, the only way to get your desired output is by calling str() on a string.

  • I know Soroush"s book is grammatically incorrect in English. I just want to put it inside an expression.
S.B
  • 13,077
  • 10
  • 22
  • 49
1

Not sure what you want it to print. Do you want it to output XYZ\'s \"ABC\" or XYZ's "ABC"?

The \ escapes next special character like quotes, so if you want to print a \ the code needs to have two \\.

string = "Im \\" 
print(string)

Output: Im \

If you want to print quotes you need single quotes:

string = 'theres a "lot of "" in" my "" script'
print(string)

Output: theres a "lot of "" in" my "" script

Single quotes makes you able to have double quotes inside the string.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Baconflip
  • 47
  • 6