The format()
method is used to format strings dynamically. It allows you to insert values into a string in a specified format by using curly braces {}
as placeholders. These curly braces are replaced with the values provided to the format()
method.
Here’s the basic syntax of the format()
method:
formatted_string = "Some text with {} and {} placeholders".format(value1, value2)
Code language: Python (python)
You can have multiple placeholders in the string, and the format()
method takes corresponding values for those placeholders as arguments.
There are several ways to use the format()
method:
- Positional Arguments: You can use positional arguments to specify the order of the values to be inserted into the string. For example:
name = "John"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)
# Output: "My name is John and I am 30 years old."
Code language: Python (python)
- Indexed Placeholders: You can use indexed placeholders to control the order of insertion explicitly. The index starts from 0. For example:
item1 = "apple"
item2 = "banana"
sentence = "I like {1} and {0}.".format(item1, item2)
print(sentence)
# Output: "I like banana and apple."
Code language: Python (python)
- Named Arguments: Instead of relying on the positional order, you can use named placeholders to insert values into the string. For example:
name = "Alice"
age = 25
sentence = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(sentence)
# Output: "My name is Alice and I am 25 years old."
Code language: Python (python)
- Formatting Specifiers: You can add formatting specifiers within the curly braces to control how the values are displayed. For instance:
number = 3.14159265359
formatted_number = "The value of pi is {:.2f}".format(number)
print(formatted_number)
# Output: "The value of pi is 3.14"
Code language: Python (python)
The format()
method provides a powerful and flexible way to create well-formatted strings with dynamic content in Python.
However, Python 3.6 introduced f-strings (formatted string literals), which provide an even more concise and readable way to format strings with dynamic values.
If you are using Python 3.6 or later, you might consider using f-strings as well.
Read More;
- What is slicing and indexing in Python explain with an example?
- What are the 7 operators in Python?
- How can I run a Python script online for free?
- What is Generator in Python With Example?
- What is class and object in Python with example?
- What is an example of a user-defined function in Python?
- Can R and Python be used together? [With Example]
- What is enumerate() in Python with an example?
- What is a for else in Python With Example?
- What is the filter() function with an Example?
- What is module and example in Python?
- What is overriding in Python with example?