Format numbers

Seymore4Head Seymore4Head at Hotmail.invalid
Sun Nov 15 14:07:12 EST 2015


On Sun, 15 Nov 2015 19:00:42 +0000, MRAB <python at mrabarnett.plus.com>
wrote:

>On 2015-11-15 17:30, Seymore4Head wrote:
>> Just screwing around making up practice problems.  I can't get the
>> format right.  I am trying to learn how to get a output line to line
>> up neatly.
>>
>> import random
>> lo=1
>> hi=10000 # I am adding or subtracting 0s from this input number
>> fm=len(str(hi)) # This counts the digits of the input number
>> print fm
>> a=random.randrange(lo,hi+1)
>> count=0
>> guess=0
>>
>> while guess != a:
>>      guess=random.randrange(lo,hi + 1)
>>      print "guess =",
>>
>>      print "{:8d}".format(guess),      #what I would like to do is use
>> the variable fm instead of the number 8 here so the number of fields
>> are the same as the input number.
>>
>>      count+=1
>>      if guess==a:
>>          print " The hidden number was",a
>>          print
>>          print "You guessed right in ",
>>      if guess >a:
>>          print " Guess Lower"
>>          hi=guess
>>      if guess < a:
>>          lo=guess
>>          print " Guess Higher"
>> print count
>> print " turns"
>>
>The part of the format placeholder that specifies the width can also be
>placeholder, like this:
>
>     print "{:{}d}".format(guess, fm)

That works
Thanks



More information about the Python-list mailing list