format Example (Format Literal)Use the format built-in to add commas to a number and pad a string with a character.
This page was last reviewed on Nov 9, 2022.
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 Literals
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.
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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.