DIfference between print() and repr()?

This is the place for queries that don't fit in any of the other categories.

DIfference between print() and repr()?

Postby datus » Sun Aug 18, 2013 11:03 am

i just started learning Python 2.7.5......and now reading documentation...and struck at this....

Code: Select all
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'


(section 3.1.2)

i didn't get it....why it is showing backslash in output????
Last edited by Mekire on Sun Aug 18, 2013 1:01 pm, edited 1 time in total.
Reason: Made title more descriptive.
datus
 
Posts: 6
Joined: Mon Jul 08, 2013 4:37 pm

Re: need help!!!

Postby stranac » Sun Aug 18, 2013 12:19 pm

That's the repr() of the string.
If you print it, you should get what you expected.
Code: Select all
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print '"Isn\'t," she said.'
"Isn't," she said.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1151
Joined: Thu Feb 07, 2013 3:42 pm

Re: need help!!!

Postby datus » Sun Aug 18, 2013 12:42 pm

can you please explain what repr() and eval() do exactly....i searched upon it but didn't get it clearly
datus
 
Posts: 6
Joined: Mon Jul 08, 2013 4:37 pm

Re: need help!!!

Postby stranac » Sun Aug 18, 2013 12:56 pm

repr() gives a printable representation of an object.

For some types(including strings), it's something that can be given to eval() to create the object.
But this is not required, and classes can make it return any string.
So basically, just the first sentence there is really important.


eval() takes a string and evaluates it as if it was python code, and returns the result.
Example:
Code: Select all
>>> eval('5 + min(1, 2)')
6

But using eval() in real code is not recommended, since it's a security risk - it allows execution of any python expressions.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1151
Joined: Thu Feb 07, 2013 3:42 pm

Re: DIfference between print() and repr()?

Postby datus » Sun Aug 18, 2013 8:04 pm

thanks !!!....now got it :D
datus
 
Posts: 6
Joined: Mon Jul 08, 2013 4:37 pm


Return to General Coding Help

Who is online

Users browsing this forum: W3C [Linkcheck] and 4 guests