4.2. Formating - JulTob/Python GitHub Wiki

Formating text

It allows for control of the presentation

data = [
  (1000, 10),
  (2000, 17),
  (2500, 100),
  (2500, -15)
]

# Header of reference
print("Revenue | Profit  | Percent")

# This template aligns and displays the data in proper format
TEMPLATE = '{revenue:>7,} | {profit:>+7} | {percent:> 7.2%}'

# Print the data rows
for revenue, profit in data:
    row = TEMPLATE.format(revenue=revenue, profit=profit, percent = profit/revenue)
    print(row)

Yeah, you guessed right: The magic is in the :>

':>'
'+' = adds a sign if positive, negatives have it all the time
# 7
numeric = Width space
'.n%' = converts to percentage and adds '%' with n precision

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
age = 33
name = 'Brian'


print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

print( name + ' is ' + str(age) + ' years old')

print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))

print('{name} was {age} years old when he wrote this book'.format(name=name, age=age))
print('Why is {name} playing with that python?'.format(name=name))

print(f'{name} was {age} years old when he wrote this book') # notice the 'f' before
the string
print(f'Why is {name} playing with that python?') # notice the 'f' before the string

# decimal (.) precision of 3 for float '0.333'
print('{0:.3f}'.format(1.0/3))
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
print('{0:_^11}'.format('hello'))
# keyword-based 'Swaroop wrote A Byte of Python'
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

print('a', end='')
print('b', end=' ')
print('c')
# ab c 
#

⚠️ **GitHub.com Fallback** ⚠️