Zone Of Makos

Menu icon

String Formatting in Python

In Python, string formatting allows you to create dynamic strings that include values that can change. String formatting is useful for creating output that includes variables or other dynamic values. There are several ways to format strings in Python, including using the % operator, the str.format() method, and f-strings. In this lesson, we'll explore each of these methods and show you how to use them effectively in your Python code.

The % Operator

The % operator is the oldest and most basic way to format strings in Python. It allows you to substitute variables and other values into a string using a placeholder syntax. The placeholder is indicated by a % character, followed by a letter that indicates the type of value that will be substituted, such as s for strings, d for integers, and f for floats.


name = "Alice"
age = 30
print("My name is %s and I am %d years old" % (name, age)) # Output: My name is Alice and I am 30 years old

The str.format() Method

The str.format() method is a newer and more flexible way to format strings in Python. It allows you to substitute values into a string using curly braces {} as placeholders, which can be named or positional. Named placeholders allow you to specify the name of the variable that will be substituted, while positional placeholders use a numeric index to indicate the position of the variable.


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

f-strings

f-strings are a newer and even more flexible way to format strings in Python. They are available starting from Python 3.6. f-strings allow you to include expressions inside the curly braces {}, which can be evaluated at runtime. This makes it easy to create complex strings that include dynamic values and computations.


name = "Alice"
age = 30
print(f"My name is {name.upper()} and I will be {age + 5} years old in 5 years") # Output: My name is ALICE and I will be 35 years old in 5 years

Conclusion

String formatting is an important feature of Python that allows you to create dynamic strings that include variables and other dynamic values. In Python, there are several ways to format strings, including using the % operator, the str.format() method, and f-strings. Each of these methods has its own advantages and disadvantages, and choosing the right method depends on your specific use case. By mastering string formatting in Python, you can create more readable, flexible, and maintainable code.