#------------------------------------------------------------------------------ # FormatNumbers.py # Illustrates str.format(). Read about the string format() function # here: https://docs.python.org/3/library/string.html #------------------------------------------------------------------------------ import random # get a random number x = random.uniform(-1000,1000) y = -x # and its negative # Create a list of different format strings. F = [] F.append("---->{0}<-------->{1}<----") # two arguments F.append("---->{1}<-------->{0}<----") # switch arguments F.append("---->{0:30}<-------->{1:30}<----") # field width 30 F.append("---->{0:<30}<-------->{1:<30}<----") # left justified in a field of width 30 F.append("---->{0:>30}<-------->{1:>30}<----") # right justified in a field of width 30 F.append("---->{0:.6}<-------->{1:.6}<----") # 6 digits of accuracy F.append("---->{0:.6f}<-------->{1:.6f}<----") # 6 digits to the right of the decimal point F.append("---->{0:^15.6f}<-------->{1:^15.6f}<----") # centered in field of width 15 F.append("---->{0:<15.6f}<-------->{1:<15.6f}<----") # same left justified F.append("---->{0:>15.6f}<-------->{1:>15.6f}<----") # same right justified F.append("---->{0:<+15.6f}<-------->{1:<+15.6f}<----") # same with + sign if positive, left justified F.append("---->{0:>+15.6f}<-------->{1:>+15.6f}<----") # same with + sign if positive, right justified F.append("---->{0:< 15.6f}<-------->{1:< 15.6f}<----") # same with a space for the sign if positive, left justified F.append("---->{0:< 15.20f}<-------->{1:< 15.20f}<----") # field expands if there are too many digits F.append("---->{0:< 15.55f}<-------->{1:< 15.55f}<----") # floats have at most 53 decimal digits of accuracy, # the rest of the field is padded with zeros # print(F) # Now print out the two numbers in different formats for s in F: print(s.format(x, y)) # end for