[Tutor] blank space after a number
Alan Gauld
alan.gauld at btinternet.com
Wed Dec 29 02:11:54 CET 2010
"Enih Gilead" <egilead at gmail.com> wrote
> a, b = 0, 1
> while b < 10:
> print '%i%i' % (a,b) + ',',
> b = b+1
If you are using string formatting it's best to get the format
string to do as much of the work as possible. In this case
forget about 'a' and just insert the zero into the string, and
similarly don't add a comma and space, just put it in the string
And for a fixed number of iterations a for loop is usually
preferable:
for b in range(1,10):
print "%02d, " % b
Does the same job.
> '''
> 01, 02, 03, 04, 05, 06, 07, 08, 09, '''
> while b < 100:
> print '%i' % (b) + ',',
> b = b+1
And exactly the same code with the limit increased
for b in range(1,101): #NB 101 to get the 100 - your while loop goes
to 99...
print "%02d, " % b
> '''
> 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17,
> 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
> 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
> 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
> 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
> 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100 '''
The %02d says print the number as two characters, padding with zeros
as needed.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list