A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_string_format_method.htm below:

Python String format() Method

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 −

Syntax

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

string.format(*args, **kwargs)
Parameters

This method accepts the following parameters −

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


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