Python String format() Method

Last Updated:

Python String format()

The format() method formats strings contain "replacement fields" surrounded by curly braces {}.

Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.

Note: If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Example

Python Compiler
txt1 = "{0} lucky number is {1}".format("John Doe", 45) txt2 = "{1} lucky number is {0}".format(45, "John Doe") print(txt1) print(txt2)

Syntax

txt.format(value1, value2, ...)

Parameter Values

ValueTypeExplanation
value1, value2, ... Required Specifies one or more values that should be formatted and inserted in the string.

Return Value

ValueExplanation
String Returns the formatted string.

More Examples

In the following example, we will use different placeholder values:

Example

Python Compiler
txt1 = "{0} lucky number is {1}".format("John Doe", 45) txt2 = "{} lucky number is {}".format("John Doe", 45) txt3 = "{name} lucky number is {num}".format(name = "John Doe", num = 45) print(txt1) print(txt2) print(txt3)

Share this Page

Meet the Author