python f string - ghdrako/doc_snipets GitHub Wiki

task_f = f"Name: {name}; Urgency Level: {urgency}"
assert task == task_f == "Name: Homework; Urgency Level: 5"

Interpolates a list object

tasks = ["homework", "laundry"]
assert f"Tasks: {tasks}" == "Tasks: ['homework', 'laundry']"

Interpolates a tuple object

task_hwk = ("Homework", "Complete physics work")
assert f"Task: {task_hwk}" == "Task: ('Homework', 'Complete physics work')"

Interpolates a dict object

task = {"name": "Laundry", "urgency": 3}
assert f"Task: {task}" == "Task: {'name': 'Laundry', 'urgency': 3}"

f-strings to interpolate expressions

Accesses an item in the list

tasks = ["homework", "laundry", "grocery shopping"]
assert f"First Task: {tasks[0]}" == 'First Task: homework'

Calls a function

task_name = "grocery shopping"
assert f"Task Name: {task_name.title()}" == 'Task Name: Grocery Shopping'

Direct calculation

number = 5
assert f"Square: {number*number}" == 'Square: 25'

format specifier

task_ids = [1, 2, 3]
task_names = ['Do homework', 'Laundry', 'Pay bills']
task_urgencies = [5, 3, 4]
for i in range(3):
print(f'{task_ids[i]:^12}{task_names[i]:^12}{task_urgencies[i]:^12}')

# Output the following lines:
           1 Do homework         5
           2 Laundry             3 
           3 Pay bills           4
def create_formatted_records(fmt):
  for i in range(3):
    task_id = task_ids[i]
    name = task_names[i]
    urgency = task_urgencies[i]
    print(f'{task_id:{fmt}}{name:{fmt}}{urgency:{fmt}}')

create_formatted_records('^15')

create_formatted_records('^18')
F-string Output Description
f"{task:*>10}" a "**homework" Right alignment, * as padding
f"{task:*<10}" "homework**" Left alignment, * as padding
f"{task:*^10}" "homework" Center alignment, * as padding
f"{task:^10}" " homework " Center alignment, space as padding
Numeric type F-string Output Description
int f"{number:b}" "1111" Binary format, using base 2
int f"{number:c}" "\x0f" Unicode representation of the integer
int f"{number:d}" "15" Decimal format, using base 10
int f"{number:o}" "17" Octal format, using base 8
int f"{number:x}" "f" Hexadecimal format, using base 16
float f"{point:.2e}" "1.23e+00" Scientific notation
float f"{point:.2f}" "1.23" Fixed-point notation with two-digit precision
float f"{point:.2g}" "1.23" General format, automatically applying e or f
float f"{point:.2%}" "123.45%" Percentage with two-digit precision
pct_number = 0.179323
print(f"Percentage: {pct_number:%}")
# output: Percentage: 17.932300%
print(f"Percentage two digits: {pct_number:.2%}")
# output: Percentage two digits: 17.93%