Lecture
Displaying Integers with the format() Function
You can use the format() function to output strings in various formats.
This process is called formatting and involves placing a colon : inside curly braces {} to specify how the data should be displayed.
Example of using the format() function
"{:format_option}".format(value)
-
{ }: Placeholder indicating where to insert the value -
:: Specifies format options
Displaying Integers
To output integers, use {:d} by placing the letter d to the right of the colon inside the curly braces.
Integer output formatting example
number = 123 # Integer output formatted = "number: {:d}".format(number) print(formatted) # "number: 123"
If you omit d, Python will automatically apply the appropriate format based on the value's data type.
Automatic type specification formatting example
number = 123 # Integer output formatted = "number: {}".format(number) print(formatted) # "number: 123"
Specifying Output Width
Placing a number after the colon sets the minimum width of the output.
For instance, {:5} sets the width of the output string to 5.
Integer output formatting example
number = 123 formatted = "number: {:5}".format(number) # Set width to 5 # Inserts two spaces before 123 print(formatted) # "number: 123",
To pad the width with zeros, prefix the width value with a 0.
Integer output formatting example
number = 123 formatted = "number: {:05}".format(number) # Set width to 5 # Inserts two zeros before 123 print(formatted) # "number: 00123"
Previous lessonTips for Using `format()` Function - indexErrorNext lessonHandling Floating-Point Numbers with the format() Function
Lessons in this chapter · String Formatting Made Easy
- 1. Inserting Variables into Strings with the format() Function
- 2. Tips for Using `format()` Function - indexError
- 3. Displaying Integers with the format() Function
- 4. Handling Floating-Point Numbers with the format() Function
- 5. Multiple-choice quiz
- 6. Case Conversion Methods upper() and lower()
- 7. Removing Leading and Trailing Whitespace with the strip() Function
- 8. String Composition Verification with isOOO() Methods
- 9. Finding the Position of a Specific Character Using find() and rfind()
- 10. Using the split() Method for Strings
- 11. How to Check if a Specific Character Exists in a String
- 12. Multiple-choice quiz
- 13. How to Format Strings with f-Strings
- 14. Comparison of format() Function and f-Strings
- 15. Using the `input` Function to Receive User Input
- 16. Indicating Invalid Values with ValueError
- 17. Coding Quiz - Splitting Strings
- 18. Multiple-choice quiz
- 19. Fill-in-the-blank quiz
Quiz
0 / 1
To output an integer using the format() function with a fixed width, what output format should be used?
number = 123
formatted_number = "number: ".format(number)
print(formatted_number) # "number: 123"
{:5}
{:.2f}
{:d}
{:s}
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help