Sunday, May 3, 2009

Print %s and %r in Python [Python 2.x]

What are the differences between %s and %r options in Python?

# Python 2.x code
string1='some text'
string2r="This string contains %r"
string2s="This string contains %s"

print string2r %string1
print string2s %string1


------------------------------------------------
Explanations

%r converts any Python object using repr()
%s converts any Python object using str().

repr() gives you the canonical representation of an object, i.e. the way you have to write in your file (strings must have at least apostrophes ); On the other hand,  str() gives you a nice representation of an object,  and this, for a string, means no apostrophes!


References:
Learn Python the hard way
http://docs.python.org


No comments:

Post a Comment

Your comment will be visible after approval.