This is an archived version of the course. Please see the latest version of the course.

Formatting strings

f-strings (formatted string literals) help make string formatting easier and more readable.

>>> name = "Josiah"
>>> count = 10
>>> possession = "cars"
>>>
>>> print(f"{name} has {count} {possession}")

You can also format floating point values.

pi = 3.14159265359
print(f"PI with three significant digits: {pi:.3}")
print(f"PI with three decimal points: {pi:.3f}")
print(f"PI with three significant digits, 9-character width is {pi:9.3}")
print(f"PI with three significant digits, 9-character width padded with 0 is {pi:09.3}")

And you can left/centre/right justify strings (giving a fixed length).

title = "Title"
print(f"| {title : <20} | {title : ^20} | {title : >20} |")

Escaping strings

If you need a quote inside your string, e.g. the boy's mother, how would you do this in Python?

>>> 'the boy's mother'
  File "<stdin>", line 1
    'the boy's mother'
             ^
SyntaxError: invalid syntax
>>>

You can escape such quotes with a backslash (\) like in C++

>>> 'the boy\'s mother'

You can also enclose your string with a different type of quote (recommended for better readability).

>>> "the boy's mother"
>>> '''the boy's mother'''
>>> 'he said, "hello"'