CMU 15-112: Fundamentals of Programming and Computer Science
Class Notes: String Formatting (Optional)



  1. String formatting with the % operator (optional)
  2. String formatting with the format method (optional)


  1. String formatting with the % operator (optional)

    format a string with %s
    breed = "beagle" print("Did you see a %s?" % breed)

    format an integer with %d
    dogs = 42 print("There are %d dogs." % dogs)

    format a float with %f
    grade = 87.385 print("Your current grade is %f!" % grade)

    format a float with %.[precision]f
    You can control how many fractional digits of a float are included in the string by changing the number to the right of the decimal point.
    grade = 87.385 print("Your current grade is %0.1f!" % grade) print("Your current grade is %0.2f!" % grade) print("Your current grade is %0.3f!" % grade) print("Your current grade is %0.4f!" % grade)

    format multiple values
    dogs = 42 cats = 18 exclamation = "Wow" print("There are %d dogs and %d cats. %s!!!" % (dogs, cats, exclamation))

    format right-aligned with %[minWidth]
    dogs = 42 cats = 3 print("%10s %10s" % ("dogs", "cats")) print("%10d %10d" % (dogs, cats))

    format left-aligned with %-[minWidth]
    dogs = 42 cats = 3 print("%-10s %-10s" % ("dogs", "cats")) print("%-10d %-10d" % (dogs, cats))

  2. String formatting with the format method (optional)

    Using .format()
    x, y, z = 3, 8, 42 s = 'Huzzah!' # {k} is replaced by the kth argument to format(): print('My favorite numbers are {0}, {1} and {2}. {3}'.format(x,y,z,s)) # You can access the arguments in any order: print('{2} {1} {0}!'.format('mice', 'chase', 'cats')) # Or even multiple times: print('{0}{1}{0}'.format('abra', 'cad'))

    Text alignment
    You can also use different specifiers to control how the strings are displayed.
    print(repr('{:<30}'.format('left aligned'))) # {:<30} = 30 characters left aligned print(repr('{:>30}'.format('right aligned'))) # {:>30} = 30 characters right aligned print(repr('{:^30}'.format('centered'))) # {:^30} = 30 characters center aligned # Text alignment with filler characters print('{:#<30}'.format('left aligned')) print('{:$>30}'.format('right aligned')) print('{:*^30}'.format('centered'))

    String/Character specifiers
    print("{!r} uses repr and shows quotes. {!s} doesn't.".format('repr()', 'str()')) print("{:c}{:c}{:c}{:c}{:c}{:c}{:c}".format(75, 105, 109, 99, 104, 101, 101))

    Numeric specifiers
    We can control what base a number is displayed in:
    print("int: {0:d}, bin: {0:b}, oct: {0:o}, hex: {0:x}, Hex: {0:X}".format(42))

    Precision specifiers
    We can control the precision with which a number is displayed:
    import math print('{:,}'.format(1234567890)) # Print with commas every 3rd place print('{:0.2e}'.format(9876543210)) # Scientific notation with 2 decimal places print('{:0.4f}'.format(math.pi * 10)) # Display the float with 4 decimal places print('{:.3%}'.format(19/22)) # Display as a percentage with 3 decimal places

    Example: degrees to radians
    This uses several .format() specifiers to display the conversion between degrees and radians in a pretty way.
    import math for i in range(0, 360, 45): print("{:c}{:>4}ยบ = {:.3f} radians".format(10209, i, math.radians(i)))