This is a built-in function. With it, we take a value (like an integer or a string
) and apply formatting to it. We receive the formatted string
.
Typically in Python, we can use string
-based methods instead of format. But sometimes the format()
built-in is needed (like for adding commas to numbers).
Here is an example of the format method. First the number 1000 is formatted as "1,000" by using a comma as the format string
.
string
of length 10.# Format this number with a comma. result = format(1000, ",") print(result) # Align to the right of 10 chars, filling with ":" and as a string. result = format("cat", ":>10s") print(result)1,000 :::::::cat
String
formatThere is a format()
method on strings. This is different from that format()
built-in. Here we insert values into substitutions in a format string
.
cat_number
" inserted into it. The same thing happens with "color."format()
. The variables are bound to names in this way.cat_color = "orange" cat_number = 10 # Use format method on string. # ... Assign variables to names in pattern. result = "cat {number} is {color}".format(number=cat_number, color=cat_color) print(result)cat 10 is orange
We can prefix a string
literal with the "f" character to have a format literal. Inside curly brackets, variables are substituted directly into the format string
.
dog_size
and dog_color
variables are placed inside the format string
.dog_color = "orange" dog_size = 100 # Use format literal. result = f"the dog weighs {dog_size} and is {dog_color}" print(result)the dog weighs 100 and is orange
For padding, consider the ljust
and rjust
methods. This can make programs simpler over using a complex (hard-to-remember) format string
.
Format strings are sometimes complex. Consider adding a def that surrounds the call to format with the complex format string
. Then just call that method.
It is possible to format strings with the format()
built-in. We can add padding. We can add commas to the string
representations of numbers.