Python String format() Method

You are Here:

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)

Output

John Doe lucky number is 45 John Doe lucky number is 45

Syntax

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

Parameter Values

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

Return Value

ValueExplanation
StringReturns 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)

Output

John Doe lucky number is 45 John Doe lucky number is 45 John Doe lucky number is 45

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Python with examples for quick and easy learning.

We are working to cover every Single Concept in Python.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author