Python String format() Method



The Python String format() method is used to is used to format string by replacing placeholders (also known as format specifiers) with corresponding values.

It works in the following way −

  • You provide a string with placeholder(s) enclosed in curly braces {}.
  • Within the curly braces, you can optionally specify formatting options, such as field width, alignment, and precision.
  • You pass the values to be substituted for the placeholders as arguments to the format() method.
  • The method replaces each placeholder with the corresponding value and returns the formatted string.

Syntax

Following is the basic syntax of the Python String format() method −

string.format(*args, **kwargs)

Parameters

This method accepts the following parameters −

  • args − These are the positional arguments that will be formatted into the string. They can be accessed inside the string using curly braces {} with positional indices.

  • kwargs − These are the keyword arguments that will be formatted into the string. They can be accessed inside the string using curly braces {} with keyword names.

Return Value

The method returns a formatted string with the specified arguments replaced with their values. The method itself returns the formatted string, and it does not modify the original string.

Example 1

In the following example, we are formatting a string by replacing placeholders "{}" with the values of variables "name" and "age" −

name = "John"
age = 30
result = "Name: {}, Age: {}".format(name, age)
print(result)  

Output

The output obtained is as follows −

Name: John, Age: 30

Example 2

Here, we use named arguments in the format() method to specify the values corresponding to placeholders "{name}" and "{age}" directly −

result = "Name: {name}, Age: {age}".format(name="Alice", age=25)
print(result)  

Output

Following is the output of the above code −

Name: Alice, Age: 25

Example 3

In the following example, we use index-based formatting to specify the order of replacement. The first placeholder "{1}" is replaced by the second argument "hello", and the second placeholder "{0}" is replaced by the first argument "world −

result = "{1}, {0}".format("world", "hello")
print(result)  

Output

The result produced is as shown below −

hello, world

Example 4

In here, we align the text to the left within a 10-character-wide space using <, and any remaining space is filled with whitespace. Then, we append "is awesome!" to the formatted text −

text = "Python"
result = "{:<10}".format(text)
print(result + "is awesome!") 

Output

We get the output as shown below −

Python    is awesome!
python_string_methods.htm
Advertisements