See new Big Daddy Toolbox: Output – format()
Here are a few examples of format() using both syntax structures. Copy and paste in your IDE then compare output to code.
print("A few format() examples:") print("Run the code, then compare output side by side with code.") print("(1) Substitution") name = "Fred" verb = "swim" noun = "bannana" print("One day {} went to {} and found a {}".format(name,verb,noun)) print() print("(2) Fixed precision at 2 with comma sep - note rounding, up only") aNumber, bNumber = 12345.6789, -12345.6721 formatString = "15,.2f" anumString = format(aNumber,formatString) bnumString = format(aNumber,formatString) print(anumString, bnumString) print() print("(3) as a percentatge with 4 decimal places") formatString = ">15.4%" anumString = format(aNumber,formatString) bnumString = format(bNumber,formatString) print(anumString, bnumString) print() #a little function to save time: def printnums(Anum,Afor,Bnum,Bfor): print("Column Border ->|"+Afor.format(Anum)+"|"+Bfor.format(Bnum)+"|") print('(4) exponential with a col width of 15') #a decimal number with two fixed decimal places formatString = "{:15e}" printnums(aNumber,formatString,bNumber,formatString) print() print("(5) format a header and then data from a string of tuples") print(" plus adding a space in from of Angler header") print() ColHeads=('Species','Weight',"Date","Angler") print('{:^18}{:<8}{:^10}{:<12}'.format('Species','Weight','Date',' '+'Angler')) champs=(['spotted bass',10.38,'1/1966','Jones'],['largemouth bass',22.25,'12/1966','Smith'],['rock bass',3.0,'1/1966','Jones']) for i in range (0,3): print('{:<18}{:>8.2f}{:>10}{:<12}'.format(champs[i][0],champs[i][1],champs[i][2]," "+champs[i][3])) print() print("(6 ) formatting a date by calling on datetime") import datetime year = 2018 month = 1 day = 19 d = datetime.datetime(year, month, day) print('{:%m/%d/%Y}'.format(d)) #note the %format specs are a part of datetime(), not format() print() print("(7) str() versus repr()") stringtest="10*2+3.9" print("This is a test calling str()"+'{!s}'.format(stringtest)) print("This is a test calling repr()"+'{!r}'.format(stringtest)) print() print('(7b) same format but calling eval inside format') print("This is a test calling str()"+'{!s}'.format(eval(stringtest))) print("This is a test calling repr()"+'{!r}'.format(eval(stringtest))) #note no quotes in repr() output