Format method

Code Examples

Example 1

Basic Variable Substitution. Similar to F-string. Know there is this method will do. Use F-string is better.

age = 25
print("I am {} years old".format(age))
# Output: I am 25 years old

Example 2

This basic example shows how format() replaces the {} placeholders with the variables name and age in the order they're provided.

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

Example 3

Position Arguments. Numbers inside the braces specify the position of arguments. {0} refers to the first argument (x), {1} to the second (y), and so on. This allows you to reuse or rearrange variables.

x = 10
y = 20
z = 30
print("Values: {0}, {1}, {2}".format(x, y, z))
print("Rearranged: {2}, {0}, {1}".format(x, y, z))
# Output:
# Values: 10, 20, 30
# Rearranged: 30, 10, 20