Guidelines

Displaying Integers with the format() Function

Using the format() function, you can output strings in various formats.

Specifying the format of the output data is called formatting, and you use a colon : inside the braces { } to define the display format.


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 putting d to the right of the colon inside the 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 use the appropriate format based on the type of the value.

Automatic type specification formatting example
number = 123 # Integer output formatted = "number: {}".format(number) print(formatted) # "number: 123"

Specifying Output Width

Using a number to the right of the colon specifies the width of the resulting string.

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 2 spaces before 123 print(formatted) # "number: 123",

If you want to pad the width with zeros, prefix the width with 0.

Integer output formatting example
number = 123 formatted = "number: {:05}".format(number) # Set width to 5 # Inserts 2 zeros before 123 print(formatted) # "number: 00123"
Mission
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}

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result