Daniel Phan
Daniel Phan

Reputation: 61

Python: Escape Characters not being interpreted

For some reason when I write an escape character in my code, the escape character is never interpreted. Could the fact that I used to work in Windows and now changed to Mac have anything to do with it? Before when I worked in windows I've never had this problem. I've tried searching but haven't found anything on this. Thank you in advance for your help!

Here is an example of what I mean:

print 'Hello \nWorld'

From this you'd expect to get:

>> Hello 
>> World

But instead IDLE prints out exactly:

>> 'Hello \nWorld'

Upvotes: 6

Views: 4607

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122232

You are not printing the string, you are printing the string literal; it is the strings representation:

>>> 'Hello\nWorld'
'Hello\nWorld'
>>> print 'Hello\nWorld'
Hello
World
>>> print repr('Hello\nWorld')
'Hello\nWorld'

Whenever you echo a variable in the Python interactive interpreter (or IDLE), the interpreter echoes the value back to you:

>>> var = 'Hello\nWorld'
>>> var
'Hello\nWorld'

Printing the value, however, outputs to the same location, but is a different action altogether:

>>> print var
Hello
World

If I were to call a function that printed, for example, and that function returned a value, you'd see both echoed to the screen:

>>> function foo():
...     print 'Hello\nWorld'
...     return 'Goodbye\nWorld'
...
>>> foo()
Hello
World
'Goodbye\nWorld'

In the above example, Hello and World were printed by the function, but 'Goodbye\nWorld' is the return value of the function, which the interpreter helpfully echoed back to me in the form of it's representation.

Upvotes: 8

Related Questions