[Tutor] Trying to write a string formatting demo

Dick Moores rdm at rcblue.com
Sun Apr 10 11:10:03 CEST 2005


Brian van den Broek wrote at 01:09 4/10/2005:
>>Hi Dick,
>>why not replace th last line with the following 2:
>>print_value = ('%' + s ) %x
>>print "%f formatted with '%s' is %s" %(x, s, print_value)
>>HTH,
>>Brian vdB
>
>Sorry, half asleep: I should also have said that I don't think it is 
>wise to call your user input string governing the formating of the float 
>`s'. Much better to choose a meaningful name, or, failing that, at least 
>not a letter that is itself a string formatting code :-)

Thanks very much, Brian. Here's what I have now, and it works.
==============================
# formatDemo.py
while True:
     print "enter a float, 'q' to quit, or nothing to accept default 
float of 1234.56789"
     x = raw_input()
     if x == "":
         print "x will be the default 1234.56789"
         x = 1234.56789
     elif x in "qQ":
         break
     else:
         x = float(x)

     floatFormatString = raw_input("enter a float format string such as 
'.4f' or '.3e': ")

     printValue = ('%' + floatFormatString ) %x
     print "%f formatted with '%s' is %s" %(x, floatFormatString, printValue)
     print
======================================

Dick




More information about the Tutor mailing list