Use format() Function in Python with Example

The `format()` function in Python is used for string formatting. It allows you to embed values into a string in a flexible way.

Basic Usage

Here’s a simple example of using `format()`:

name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

Output:

My name is Alice and I am 30 years old.

Positional and Keyword Arguments

You can also use positional and keyword arguments:

Positional Arguments:

formatted_string = "I love {} and {}".format("Python", "JavaScript")
print(formatted_string)

Output:

I love Python and JavaScript

Keyword Arguments:

formatted_string = "My favorite fruit is {fruit} and my favorite color is {color}.".format(fruit="apple", color="blue")
print(formatted_string)

Output:

My favorite fruit is apple and my favorite color is blue.

Indexing and Repeating

You can refer to the same value multiple times or in a different order:

formatted_string = "The numbers are {0}, {1}, and {0} again.".format(10, 20)
print(formatted_string)

Output:

The numbers are 10, 20, and 10 again.

Formatting Numbers

You can also format numbers:

number = 1234.56789
formatted_string = "Formatted number: {:.2f}".format(number)
print(formatted_string)

Output:

Formatted number: 1234.57

In this example, `{:.2f}` formats the number to 2 decimal places.

Padding and Alignment

You can align and pad strings:

formatted_string = "{:<10} {:^10} {:>10}".format("left", "center", "right")
print(formatted_string)

Output:

left center right

Here, `<` aligns to the left, `^` centers, and `>` aligns to the right, with a width of 10 characters.

The `format()` function is quite powerful and can be used for many different formatting scenarios.