How does format () work in Python?

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:

  1. 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)
  1. 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)
  1. 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)
  1. 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;

  • I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

    View all posts

Leave a Comment