Python String format() Method

Example

Insert the price into the placeholder, the price should be in fixed-point, two decimal place format:

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

Run Instance

Definition and Usage

The format() method formats the specified values and inserts them into the placeholders of the string.

Placeholders are defined using curly braces {} for more information on placeholders, see the "Placeholders" section below.

The format() method returns a formatted string.

Syntax

string.format(value1, value2...)

Parameter Value

Parameter Description
value1, value2...

Required. One or more values that should be formatted and inserted into the string. The values can be numbers, used to specify the position of the element to be removed.

These values can be a list of values separated by commas, a key=value list, or a combination of both.

These values can be of any data type.

Placeholders

Placeholders can be identified using named indices {price}, numbered indices {0}, or even empty placeholders {}.

Example

Use different placeholder values:

txt1 = "My name is {fname}, I'am {age}".format(fname = "Bill", age = 64)
txt2 = "My name is {0}, I'am {1}".format("Bill",64)
txt3 = "My name is {}, I'am {}".format("Bill",64)

Run Instance

Formatting Types

Within the placeholder, you can add formatting types to format the result:

:< Try It Left-align the result (within the available space)
:> Try It Right-align the result (within the available space)
:^ Try It Center the result (within the available space)
:= Try It Place the sign at the leftmost position
:+ Try It Use plus sign to indicate whether the result is positive or negative
:- Try It The negative sign is only used for negative values
: Try It Insert an extra space before the positive number using space (use minus sign before negative number)
:, Try It Use comma as the thousand separator
:_ Try It Use underscore as the thousand separator
:b Try It Binary Format
:c Convert the value to the corresponding unicode character
:d Try It Decimal Format
:e Try It Scientific Format, with Lowercase E
:E Try It Scientific Format, with Uppercase E
:f Try It Fixed-point Number Format
:F Try It Fixed-point Number Format, Displayed in Uppercase (Display inf and nan as INF and NAN)
:g General Format
:G General Format (Use uppercase E for scientific notation)
:o Try It Octal Format
:x Try It Hexadecimal Format, Lowercase
:X Try It Hexadecimal Format, Uppercase
:n Number Formatting
:% Try It Percentage Formatting