Slides 04 String Formatting
Slides 04 String Formatting
String formatting
Python basics
Michael Burrell
Format specifiers
Format specifiers
There are many format specifiers that are defined in Python,
but the major ones are:
%f — print out a float. You can optionally provide
two leading numbers, one to give the total length
and one to give the number of digits after the
decimal point. E.g., %10.3f formats as 10
characters, with 3 of them being after the
decimal point. You can leave out the first number
(e.g., %.3f)
%e — like %f, but prints out using scientific notation
%g — like %f unless the number is very big or very
close to 0, in which case it uses %e instead
f Strings
f Strings example
Escape sequences
Escape sequences
In Python, you can put special characters into a string by
using a backslash (\) as an escape. Some popular escape
sequences:
\’ — make a literal ’ character
\” — make a literal ” character
\n — make a newline character, which puts the rest
of the text on the following line
\t — makes a horizontal tab character, which adds
horizontal space until it gets to a column that’s a
multiple of 8. It can be used for lining things up
\\ — for when you need a literal backslash character
in your string
Michael Burrell String formatting