Extra Topic: String Formatting (with f strings)


Note: extra topics are not in CS Academy, but are required and can appear on any future homework, writing session, quiz, or exam.
print('Using ints with f-strings:') n = 31416 print(f'Example 1: |{n}| (plain, with no specifier)') print(f'Example 2: |{n:8}| (now with a field-width of 8)') print(f'Example 3: |{n:08}| (now with leading 0s)') print(f'Example 4: |{n:8,}| (now grouped by commas)') print(f'Example 5: |{n:X}| (in hex uppercase)') print(f'Example 6: |{n:x}| (in hex lowercase)') print(f'Example 7: |{n:b}| (in binary)') print(f'Example 8: |{n:_b}| (in binary grouped by underscores)')

print('Using floats in f-strings:') x = 314.15926535 print(f'Example 1: |{x}| (plain, with no specifier)') print(f'Example 2: |{x:.2f}| (now with 2 digits of float precision)') print(f'Example 3: |{x:8.2f}| (now with a field-width of 8)') print(f'Example 4: |{x:08.2f}| (now with leading 0s)')

print('Using strings with f-strings:') s = '15-112' print(f'Example 1: |{s}| (plain, with no specifier)') print(f'Example 2: |{s:15}| (now with a field-width of 15)') print(f'Example 3: |{s:>15}| (now right-aligned)') print(f'Example 4: |{s:^15}| (now centered)') import sys if sys.platform == 'brython': print('Example 5: skipping this since it will not run properly in brython') else: print(f'Example 5: |{s:*^15}| (now with * as the fill character)')