Python String format

Python String format() method returns a new string value that is formatted using the placeholders in given string and the values passed as arguments to the format() method.

In this tutorial, we will learn the syntax and examples for format() method of String class.

Syntax

The syntax of String format() method in Python is

str.format(*args, **kwargs)

where

Parameter Required/Optional Description
*args Optional Positional arguments.
**kwargs Optional Keyword arguments.

Example

In this example, we will take a string, and format this string with positional arguments passed to the format() method.

Python Program

x = 'Hello {}! Welcome to {}.'
result = x.format('XYZ', 'New World')
print(result)

Output

Hello XYZ! Welcome to New World.

Explanation

{}s in the string x are placeholders. Positional arguments are loaded into these placeholders respectively.

format with Keyword Arguments

In this example, we will take a string, and format this string with keyword arguments passed to the format() method.

Python Program

x = 'Hello {name}! Welcome to {country}.'
result = x.format(name='XYZ', country='New World')
print(result)

Output

Hello XYZ! Welcome to New World.

format with Positional and Keyword Arguments

In this example, we will take a string, and format this string with both positional and keyword arguments passed to the format() method.

Python Program

x = '{} Hello {name}! Welcome to {country}. '
result = x.format('Greetings!', name='XYZ', country='New World')
print(result)

Output

Greetings! Hello XYZ! Welcome to New World.

Conclusion

In this Python Tutorial, we learned how to format a given string with placeholders; positional and keyword arguments, using String method – format().