[Tutor] Trying to write a string formatting demo

Brian van den Broek bvande at po-box.mcgill.ca
Sun Apr 10 10:09:48 CEST 2005


Brian van den Broek said unto the world upon 2005-04-10 03:58:
> Dick Moores said unto the world upon 2005-04-10 03:38:
> 
>> I'm trying to write a string formatting demo, just for things like 
>> %.4f,  %.3e, and %.3g.
>>
>> Here's what I have, but of course it doesn't work. What should the 
>> print statement be?
>>
>> ========================
>> x = raw_input("enter a float: ")
>> if x == "":
>>     print "x will be the default 1234.56789"
>>     x = 1234.56789
>> else:
>>     x = float(x)
>>
>> s = raw_input("enter a float format string such as '.4f' or '.3e': ")
>>
>> print "%f formatted with '%s' is %s" % (x,s,x)
>> ==========================
>>
>> Thanks,
>>
>> Dick Moores
>> rdm at rcblue.com
> 
> 
> 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 :-)

Best,

Brian



More information about the Tutor mailing list