Python String Formatting – Tutorial with Examples

In Python, strings are used to represent text-based data, and they are an essential part of any program. String formatting is a way to insert values into a string and create a new, formatted string. There are several ways to format strings in Python, and this article will cover some of the most commonly used methods.

String Concatenation

The simplest way to format strings in Python is by using string concatenation. This involves combining multiple strings into a single string using the + operator. Here is an example:

name = "John"
age = 32

# Using string concatenation
string = "My name is " + name + " and I am " + str(age) + " years old."

print(string)

Output:

My name is John and I am 32 years old.

In this example, we have created a string by concatenating several strings and an integer. We had to convert the integer to a string using the str() function before we could concatenate it with the other strings.

String Interpolation

String interpolation is another way to format strings in Python. This involves using placeholders in the string and then replacing them with values using the format() method. Here is an example:

name = "John"
age = 32

# Using string interpolation
string = "My name is {} and I am {} years old.".format(name, age)

print(string)

Output:

My name is John and I am 32 years old.

In this example, we have used curly braces {} as placeholders in the string. We then used the format() method to replace the placeholders with the values of name and age. The format() method takes the values to be inserted as arguments and inserts them into the string in the order they are given.

f-Strings

f-strings are a newer way to format strings in Python, and they are available in Python 3.6 and later. f-strings are similar to string interpolation, but they use the f prefix before the string and expressions inside curly braces {} to evaluate and insert values into the string. Here is an example:

name = "John"
age = 32

# Using f-strings
string = f"My name is {name} and I am {age} years old."

print(string)

Output:

My name is John and I am 32 years old.

In this example, we have used f-strings to format the string by using expressions inside curly braces {}. The expressions are evaluated and the result is inserted into the string. f-strings are a concise and readable way to format strings in Python.

Conclusion

In this article, we have covered three ways to format strings in Python: string concatenation, string interpolation, and f-strings. Each method has its own advantages and disadvantages, and the choice of which method to use depends on the requirements of your program and personal preference. No matter which method you choose, the end result is a new, formatted string that you can use in your program.

Leave a Reply

Your email address will not be published. Required fields are marked *