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 −
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.
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 1In 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: 30Example 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: 25Example 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, worldExample 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4