String Formatting in Python

When I first started programming, I used to concatenate a string to add dynamic values in a string which used to look something like this:

username = "John"
greeting = "Hey " + username + ", Good morning!"

String concatenation in Python.

This worked completely fine. But as I started to add more values, It started becoming hard to maintain. Take a look at the example given below.

OTP = 123456
TEAM_NAME = "Python"

message = "Hello " + username + ", \n" \
    + "Your OTP is " + str(OTP) + "\n" \
    + "\nThanks, \nTeam " + TEAM_NAME

String concatenation with multiple variables.

So Let’s look at some of the better ways to do the string formatting in Python apart from string concatenation.

1. Using % sign and type matching placeholder

One of the old ways to format a string is to use % sign and placeholder which matched the type of variable.

message = """Hello %s, 
Your OTP is %d.
- Team %s""" % (username, OTP, TEAM_NAME)

In the above example, I have used a multi-line string along with a placeholder where I want to place the value of variables. If you observe properly, I have used %s for strings and %d for integer values also variables in tuple that we used after % are in order of their position in the string.

2. Using .format method

Another way to format a string is to use the .format method. Similar to the previous method we have seen, we have to use a placeholder where we want variable values except we don’t have to use type matching placeholder rather there are different ways in which we can use placeholders.

  • Use index position in {}

  • Use blank placeholder with open-close curly braces

  • Use variable in {}

Let’s have a look at them one by one.

i. Use index position in {}

message = """Hello {0}, 
Your OTP is {1}.
- Team {2}""".format(username, OTP, TEAM_NAME)

In the given example, I am passing positional arguments to the format function. Then we have to use the index of the argument inside curly braces as a placeholder in a string. This can be in any order, we just have to make sure that we are using the right index while using placeholders.

message = """Hello {0}, 
Your OTP is {2}.
- Team {1}""".format(username, TEAM_NAME, OTP)

This example will give the same result as the previous one. Observe how I have changed the position of TEAM_NAME and OTP while passing the arguments.

ii. Use blank placeholder with open-close curly braces

message = """Hello {}, 
Your OTP is {}.
- Team {}""".format(username, OTP, TEAM_NAME)

Like in the previous example, We are passing arguments to the format function. But instead, we haven’t mentioned any index number in curly braces. In this case, we have to make sure that arguments that are passed to the format function are in order. Swapping the position of variables will give us different results.

iii. Pass keyword argument to format function

message = """Hello {username}, 
Your OTP is {OTP}.
- Team {TEAM_NAME}""".format(
    username=username, OTP=OTP, TEAM_NAME=TEAM_NAME
)

format works just like any other function. We can also pass keyword arguments to this function and then we can use these arguments as placeholders with curly braces around it. This way we can make sure that we are using the right placeholder at the right place. We can also do the following in this case:

message = """Hello {user}, 
Your OTP is {OTP}.
- Team {TEAM_NAME}""".format(
    user=username, OTP=OTP, TEAM_NAME=TEAM_NAME
)

You can use any name for your keyword argument, just make sure that you’re passing the right values to them.

3. F-String in Python

F-strings are my favorite ones and I used them a lot while programming in Python. Instead of passing any arguments to any function we can directly use variables as placeholders surrounded by curly braces. We have to use f at the start of the string for it to work. Let’s have a look at the example given below:

message = f"""Hello {username}, 
Your OTP is {OTP}.
- Team {TEAM_NAME}"""

Here we have used f at the very start of the string (before quotes) and then used actual variables that we want to use as placeholder which makes it super easy to manage and more readable.

Performance of all methods for string formatting

Okay, So we have understood the different methods by which we can use string formatting. Let’s also compare the performance of all of them. To compare results I have added each method in a loop and it iterates it for n number of times (In our case, n = 10000000).

Here’s an example for f-string which is iterated for N times. (You can see I was able to perform subtract operation in curly braces which is something I like the most about F-strings)

Now let’s have a look at the results.

All differences shown in the above image are in seconds. As you can see, the F-string performed much better compared to all other methods. Whereas, the format method with keyword argument took more than double the time than any other method. This may or may not affect your project depending on what you are doing in your project but It is always best to have some knowledge about these metrics.

Conclusion

We can use different methods to format the string in Python. For me, the F-string method is work with which also happens to be the fastest one of all.

Let me know which one you use. Follow me on Twitter (X) for more daily tips on Python.