
December 19th, 2012, 02:32 PM
|
|
Registered User
|
|
Join Date: Dec 2012
Posts: 2
Time spent in forums: 8 m 47 sec
Reputation Power: 0
|
|
|
Help with format characters.
I am new to python and have a little question about format characters.
I did a few tests with them(I think the best way to learn is try it out) and I can't find the difference between %r and %s. It works with a floating point number, a number and strings. While all the others don't work with at least one of them. I already find out that %s converts the variable into a string with str() and %r with repr(). I also thought that %r is used for debugging.
A little example:
Code:
string = "This is just a string."
number = 3
floating_point = 3.0
# all the variables with %r
print "This is what I'm printing: %r" % string
print "This is what I'm printing: %r" % number
print "This is what I'm printing: %r" % floating_point
# all the variables with %s
print "This is what I'm printing: %s" % string
print "This is what I'm printing: %s" % number
print "This is what I'm printing: %s" % floating_point
# all the variables with %c(I know it will fail with 2 of them #
# because it is used for things with 1 character).
print "This is what I'm printing: %c" % string
print "This is what I'm printing: %c" % number
print "This is what I'm printing: %c" % floating_point
Output:
Code:
This is what I'm printing: 'This is just a string.'
This is what I'm printing: 3
This is what I'm printing: 3.0
This is what I'm printing: This is just a string.
This is what I'm printing: 3
This is what I'm printing: 3.0
Traceback (most recent call last):
File "3.py", line 23, in <module>
print "This is what I'm printing: %c" % string
TypeError: %c requires int or char
|