[Tutor] The % operator (original) (raw)
Brian van den Broek bvande at po-box.mcgill.ca
Tue Jul 6 04:24:17 CEST 2004
- Previous message: [Tutor] The % operator
- Next message: [Tutor] The % operator
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Bernard Lebel said unto the world upon 05/07/2004 16:46:
Hello,
I have been reading many examples where the % operator is used, and I know I have read in the docs its meaning. However I can't seem to be able to retrieve it, and a search doesn't return interesting results. So I'm turning to you, honorable people: could someone be kind to explain to me what is doing the % operator, how it works, or at least point me to the appropriate page in the Python documentation?
Thank you Bernard
Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor
Hi Bernard,
In the Python Library reference, try: 2.3.6.2 String Formatting Operations.
There are more details to it than I am about to mention, and I am giving my intuitive understanding rather than an "official" explanation (I am a relative newbie, too). But the rough idea is that it that string formatting lets you define a text string with some "holes" in it. The holes are marked by the % character and have various sorts. %s marks a hole to be filled by a string, %i a hole to be filled by an integer, %03i a hole for an integer with at least 3 places, leading 0's added if need be, etc.
You use it by having a string with n %-holes followed by "%" and either a single element of an n-tuple of elements (of the right sorts).
String formatting lets you build "string templates" and allows you to fit long string definitions onto an 80-character line, etc.
Some examples:
IDLE 1.0.3
h = "It is my very favourite language. I'd be lost without it." print "%s is fun! I use it %s day. %s" %("Python", "every", h) Python is fun! I use it every day. It is my very favourite language. I'd be lost without it. a = 1 m = "This is a %s. It has had %i iterations so far." while a < 6: print m %("While loop", a) a = a + 1
This is a While loop. It has had 1 iterations so far. This is a While loop. It has had 2 iterations so far. This is a While loop. It has had 3 iterations so far. This is a While loop. It has had 4 iterations so far. This is a While loop. It has had 5 iterations so far.
c = "This is a %s. It has had %03i iterations so far." for b in range(5): print c %("For loop", b + 1)
This is a For loop. It has had 001 iterations so far. This is a For loop. It has had 002 iterations so far. This is a For loop. It has had 003 iterations so far. This is a For loop. It has had 004 iterations so far. This is a For loop. It has had 005 iterations so far.
Best,
Brian vdB
- Previous message: [Tutor] The % operator
- Next message: [Tutor] The % operator
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]