HomeSearch

Python format Example (Format Literal)

Use the format built-in to add commas to a number and pad a string with a character.
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.

Padding: A ":" character is applied as padding. The "greater than" character, followed by 10s, means right-align in a string of length 10.

Python program that uses format # 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) Output 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.

Number: 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.

Python program that uses format 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) Output 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.

Python program that uses format literal dog_color = "orange" dog_size = 100 # Use format literal. result = f"the dog weighs {dog_size} and is {dog_color}" print(result) Output 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.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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls