Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
like image 472
Daniel Phan Avatar asked Oct 08 '12 16:10

Daniel Phan


1 Answers

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.

like image 99
Martijn Pieters Avatar answered Sep 20 '22 01:09

Martijn Pieters