You are invited to Log in or Register a free Frihost Account!

Python the Hard Way, %s, %r, %d

After a huge break in Python, with one quick look a couple of weeks ago, I am back into Python Smile Dunno why I stop. I really love it lol.

In order to refresh properly, I decided to go through a beginners learning program quickly, and I chose Learn Python the Hard Way.

Although I am progressing quite quickly, I was in for a happy surprise when it goes into a few things that I didn't learn from where I am up to in the MIT (not really that far lol.)

One basic syntactical new thing was the whole %s, %r %d thing. I don't even know what you call it.

It works like this:

inside a string, you can put a variable by replacing the variable with %s, %r or %d. (There may well be other letters).

This saves the awkward gaps when you attempt to put commas and variables, such as the line:
print "Well,", user_name, "it is your turn."

Which I have until now been unsure in some cases how to solve (the gap problem).

The syntax of using the % is as follows:

print "Well, %s, it is your turn." % variable

or for multiple variables in a string,

print "Well, %s, it is now the turn of %s." % (variable1, variable2)

The 3 types I have described are %s, %r and %d.

%s is for strings, in which quotes will not surround.

%r is for any type, and quotes will surround, and

%d is for integers.

2 blog comments below

This is called "string formatting" and allows to convert any type of data ( on the right ) to a string representation ( on the left ). See for example many ways how to represent a floating point value as a string:


>>> "%d" % 3.14
>>> "%f" % 3.14
>>> "%.3f" % 3.14
>>> "%e" % 3.14
>>> "%s" % 3.14

You can add parameter ( like shown in case of %f ) to be more specific with how to format the string; here: %.3f would mean to provide a three-digits formatting of 3.14.

%r stands for the Python internal representation of a variable. With 3.14 you get something interesting:


>>> "%r" % 3.14

Best Regards ... Axel
amagard on Mon Dec 19, 2011 12:29 pm
OoO thanks!

Very useful Smile
Hello_World on Wed Dec 21, 2011 2:16 am

© 2005-2011 Frihost, forums powered by phpBB.