Rik Schoonbeek
Rik Schoonbeek

Reputation: 4460

Does escaping work differently in Python shell? (Compared to code in file)

In a Python 3.7 shell I get some unexpected results when escaping strings, see examples below. Got the same results in the Python 2.7 shell.

A quick read in the Python docs seems to say that escaping can be done in strings, but doesn't seem to say it can't be used in the shell. (Or I have missed it).

Can someone explain why escaping doesn't seem to work as expected.

Example one:

input: >>> "I am 6'2\" tall"

output:
'I am 6\'2" tall'

while >>> print("I am 6'2\" tall")

returns (what I expected):
I am 6'2" tall

(I also wonder how the backslash, in the unexpected result, ends up behind the 6?)

Another example:

input: >>> "\tI'm tabbed in."

output: "\tI'm tabbed in."

When inside print() the tab is replaced with a proper tab. (Can't show it, because stackoverflow seems the remove the tab/spaces in front of the line I use inside a code block).

Upvotes: 0

Views: 33

Answers (2)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22041

Basically your terminal is calling repr magic method of the string when you enter it in terminal as is. In the same time when you call print over the string it calls __str__ method on it:

s = "I am 6'2\" tall"
s.__repr__() 
'\'I am 6\\\'2" tall\''
s.__str__()
'I am 6\'2" tall'

See more on that comparison between those two methods: str vs. repr and that SO Difference between __str__ and __repr__? question.

Good Lack in your future python adventures.

Upvotes: 2

deceze
deceze

Reputation: 522155

The interactive shell will give you a representation of the return value of your last command. It gives you that value using the repr() method, which tries to give a valid source code representation of the value; i.e. something you could copy and paste into code as is.

print on the other hand prints the contents of the string to the console, without regards whether it would be valid source code or not.

Upvotes: 2

Related Questions