Format numbers

MRAB python at mrabarnett.plus.com
Sun Nov 15 14:00:42 EST 2015


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)




More information about the Python-list mailing list