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"
CodePudding user response:
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 therepr()gets called not__str__which is called byprintfunction.)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"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"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 bookis grammatically wrong in English. I just want to put in inside an expression.
CodePudding user response:
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.
