Ways to Insert a Python Variable into a String

As a Python developer, I’ve found that one of the most common tasks is putting a variable inside a string.

Whether I’m building a report for a client in New York or personalizing an email for a user in California, I always need to format text dynamically.

There are several ways to do this in Python. Some are old, some are new, and some are just plain better for modern development.

In this tutorial, I will show you the most effective methods for inserting variables into strings, based on my firsthand experience.

Method 1: Use F-Strings (The Modern Way)

Since Python 3.6, I’ve almost exclusively used f-strings. They are fast, readable, and very easy to type.

You just need to add the letter f before your string and put your variables inside curly braces {}.

Here is an example where I’m calculating the total cost of a tech gadget, including Texas sales tax:

# Using f-strings to format a price
product = "MacBook Pro"
price = 1999.99
tax_rate = 0.0825  # 8.25% Texas sales tax

# Inserting variables directly into the string
message = f"The total price for the {product} in Austin, TX is ${price * (1 + tax_rate):,.2f}."

print(message)

I executed the above example code and added the screenshot below.

python variable in string

I love this method because I can even do math right inside the braces. The :,.2f part ensures the price looks professional with a comma and two decimal places.

Method 2: Use the .format() Method

Before f-strings came along, the .format() method was my go-to. I still use it today when I need to reuse the same variable multiple times in a long paragraph.

It uses empty curly braces as placeholders and then fills them in using the arguments you provide at the end.

Let’s look at a travel itinerary example:

# Using .format() for a travel summary
city_from = "San Francisco"
city_to = "Chicago"
airline = "United Airlines"

# Using positional placeholders
summary = "Your flight from {} to {} on {} is confirmed.".format(city_from, city_to, airline)

print(summary)

I executed the above example code and added the screenshot below.

string variable

One trick I’ve learned is that you can also name the placeholders. This makes the code much easier to read if you have five or six variables in one sentence.

Method 3: Use the % Operator (The Old Style)

If you have ever worked with C or Java, this method will look very familiar to you. It uses the % symbol as a placeholder.

While this is an older “legacy” way of doing things, you will still see it in older Python scripts or when working with certain logging libraries.

Here is how I would use it for a simple weather alert:

# Using the % operator for a weather update
city = "Miami"
temperature = 85
condition = "sunny"

# %s is for strings, %d is for integers
alert = "The weather in %s is currently %d degrees and %s." % (city, temperature, condition)

print(alert)

I executed the above example code and added the screenshot below.

python string variable

I usually avoid this in new projects because it can get messy if you accidentally mix up a string (%s) with a number (%d).

Method 4: Use String Template Class

Sometimes I need to let users provide their own templates, but I don’t want them to have the power to execute code (which f-strings can do).

In those cases, I use the Template class from the string module. It’s safer for handling data that comes from outside sources.

Here is an example of a standard US business greeting:

from string import Template

# Creating a safe template
greeting_template = Template("Hello $name, welcome to our headquarters in $location!")

# Substituting values
message = greeting_template.substitute(name="Sarah", location="Seattle")

print(message)

This method uses the $ sign, which is very common in other scripting languages, making it intuitive for beginners.

Which Method Should You Use?

In my experience, you should use f-strings for about 95% of your work. They are the fastest and cleanest option available in modern Python.

I only switch to .format() if I’m working on a very old system (Python 2.7 or 3.5) or if I need to build a complex template that gets reused.

If you are worried about security, like when building a web app where users can edit their own templates, then the Template class is your safest bet.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.