Python string format() method with example

The format() method in Python is a method associated with string handling. It formats the given string into a more desirable, neat, or pretty output. This method is highly useful in constructing dynamic strings, as it provides various ways to format strings, including dynamic substitutions, formatting sets of values, as well as fixed values.

Syntax:

str.format(*args, **kwargs)

str: The string on which the format() function is called. This string can contain literal text or replacement fields denoted by braces {}. Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument.

*args: Optional. A tuple specifying positional arguments. These arguments are inserted at {} placeholders using index numbers within the braces.

*kwargs: Optional. A dictionary specifying keyword arguments. These arguments are inserted at {} placeholders using keyword names within the braces.

How to use the format() method:

print("Hello, {}. You are {} years old.".format("Alice", 25))

Output:

Hello, Alice. You are 25 years old.

Example 1

You can also use positional and keyword arguments to specify the values to be formatted.

print("{0} and {1}".format('Python', 'Java'))

Output:

Python and Java

Example 2

0 and 1 are the indexes of the arguments in the format() function.

print("{name} loves {food}".format(name="Sam", food="pizza"))

Output:

Sam loves pizza

Example 3

The format() method to generate a formatted string with year, month, and day.

year = 2023
month = 5
day = 24

print("The date is {year}-{month:02d}-{day:02d}".format(year=year, month=month, day=day))

Output:

The date is 2023-05-24

Example 4

Using a dictionary with the format() method.

person = {'name': 'Alice', 'age': 25}

print("My name is {name} and I am {age} years old.".format(**person))

Output:

My name is Alice and I am 25 years old.

Leave a Reply

Your email address will not be published. Required fields are marked *