#------------------------------------------------------------------------------ # FormatNumbers1.py # Illustrates using the str.format() function to control how numbers and # strings are printed. Read about the string format() function in section # 8.16 of the online text. #------------------------------------------------------------------------------ import random # Create a random number generator rng = random.Random(242) # Using a seed produces the same 'random' numbers # every time you run the program # Create two lists A and B of random numbers to format A = [] for i in range(20): A.append(rng.uniform(0,999)) # end for # here's a shorter, equivalent method for building a list B = [rng.uniform(0,999) for i in range(20)] # print them in three columns using format() function, third column are same # numbers as the first, but formatted differently. print("{0:<19}{1:<24}{0}".format("List A", "List B")) format_string = "{0:<19.10f}{1:<23.15f}{0:>10.5f}" for i in range(20): print(format_string.format(A[i],B[i])) # end for