Home
Python
format Example (Format Literal)
Updated Nov 9, 2022
Dot Net Perls
Format. 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).
An example. 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.
Detail A ":" character is applied as padding. The "greater than" character, followed by 10s, means right-align in a 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 format. There is a format() method on strings. This is different from that format() built-in. Here we insert values into substitutions in a format string.
Detail The "{number}" pattern in the string has the "cat_number" inserted into it. The same thing happens with "color."
Tip We assign names to variables in the argument list of 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
Format literal, f. 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.
String Literal
Here The 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
Padding. For padding, consider the ljust and rjust methods. This can make programs simpler over using a complex (hard-to-remember) format string.
String Padding
Format, some notes. 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.
def
A review. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen