Dick Moores <rdm <at> rcblue.com> writes: > So now that I know better, I'm trying to write the beginnings of a > general setPrecision() function using format strings. However, it > appears that a variable cannot be used instead of the ".2" in > > "%.2f" % 2.234234 <snip> > How to do this?
You could use simple string concatenation: >>> "%." + str(2) + 'f' '%.2f' >>> "%." + str(4) + 'f' '%.4f' Or use format strings to create other format strings, by escaping the '%' with '%%'. E.g.: >>> "%%.%df" % 2 # the '%%' will be changed to '%' in the result '%.2f' >>> "%%.%df" % 4 '%.4f' >>> s1 = "%%.%df" % 2 >>> print s1, s1 % 3.41234 '%.2f', '3.41' >>> s2 = "%%.%df" % 4 >>> print s2, s2 % 3.41234 '%.4f', '3.4123' >>> ("%%.%df" % 2) % 3.23423 '3.23' Yours, Andrei _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor