4 Ways to Insert a Python Variable in a String

There are four common methods that will allow you to add Python variables in a string, including: the comma, the modulus operator, string format and f-strings. Here’s how they work.

Written by Bisola Olasehinde
Published on May. 03, 2024
4 Ways to Insert a Python Variable in a String
Image: Shutterstock / Built In
Brand Studio Logo

There are times when you’ll need to include a variable or non-string data type into a string in Python. It can be a confusing process, so I’ve outlined four different ways to add a variable in a Python string with example code.

Different Ways to Insert Python Variables in a String

  1. The comma
  2. The % operator
  3. String format method
  4. F-strings

 

How to Put a Python Variable in a String

1. The Comma

The most common way to separate strings and variables is with a comma, as shown below:

>>> name = “John”

>>> age = 16
>>> height = 1.72
>>> print(“Name:”, name, “; Age:”, age, “; Height:”, height, “m”)

Name: John ; Age: 16 ; Height: 1.72 m

This doesn’t give a lot of ability to customize the output and still make everything look good. We also need to note that each comma separation is a “space” in the output string.

We can do better.

More on Python5 Ways to Find the Index of a Substring in Python

2. The % operator

The % operator, or modulus operator, is an older method, but you’ll still see it quite frequently. In fact, I use it a lot, too.

>>> print(“Name: %s; Age: %d; Height: %fm” % (name, age, height))
Name: John; Age: 16; Height: 1.720000m

This gives us more flexibility, but there are two major limitations.

  1. You can’t include any data types, such as list or datetime.
  2. %s is for string, %d is for integer (int) and %f for float. You mustn’t mistake one for the other.
>>> print(“Name: %s; Age: %f; Height: %dm” % (name, age, height))
Name: John; Age: 16.000000; Height: 1m

With the example above, there’s no error because the data types were convertible.

Therefore, Python automatically casts the necessary data type onto the input.

However, there are some floats, like “infinity,” that can’t be converted to int.

>>> import math
>>> math.inf
inf
>>> int(math.inf)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
OverflowError: cannot convert float infinity to integer

>>> print(“Infinity %s” % math.inf)
Infinity inf

>>> print(“Infinity %f” % math.inf)
Infinity inf

>>> print(“Infinity %d” % math.inf)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
OverflowError: cannot convert float infinity to integer

When there are more than one arguments for the % operator, it has to be a tuple. And lastly, you can specify the length of a float as shown below: dot followed by the number of decimal places.

>>> print(“Name: %s; Age: %d; Height: %.1fm” % (name, age, height))
Name: John; Age: 16; Height: 1.7m

3. The String Format Method

Python string has a format method that lets you insert any data type. It’s very similar to the % operator with `%s` or `%d` or `%f` replaced with `{}`, but better.

>>> print(“Name: {}; Age: {}; Height: {}m”.format(name, age, height))
Name: John; Age: 16; Height: 1.72m

The format method is better for a few reasons, including:

  1. You don’t have to be sure about the data type.
  2. You can insert any data type.
  3. You can repeatedly use a value by indexing.
>>> from datetime import datetime

>>> print(“{} test scores in a list {} on {}”.format(name, [23, 25.5, 28], datetime.now()))
John test scores in a list [23, 25.5, 28] on 2021–03–15 13:30:39.754769

# Indexing like a list
>>> print(“{0} is {3}. {0} loves {1}, {2} and {0}”.format(name, ‘Harry Potter’, ‘ice cream’, age))
John is 16. John loves Harry Potter, ice cream and John

# Another form of index
>>> print("{fname} {lname} is {age}".format(age=16, fname="John", lname="Snow"))

John Snow is 16

The last index example also illustrates that the values in the format method can be expressed as a list of key-value pairs.

4. F-Strings

Another attractive option is the formatted string literal, f-string.

>>> print(f”{name} is {age}, and today is {datetime.now().strftime(‘%Y-%m-%d’)}”)
John is 16, and today is 2021–03–15

The main advantage is that it lets you readily know where a value is, and I just think it looks good. But the downsides are:

  1. It requires Python 3.6 or greater. You have to be certain of that to avoid an error.
  2. You can’t include a backslash in the expression part (inside `{}`).
  3. This also means that you can’t include `”` without getting a SyntaxError.
A tutorial on how to add a variable in a string in Python. | Video: Python & Ubuntu

More on PythonPython List and List Manipulation Explained

 

Best Method for Inserting a Python Variable in a String

  • The string format method is the best option in my opinion.
  • F-string looks nice, but it requires Python version 3.6 or greater to do it, making it less accessible.
  • The % format isn’t a bad option.
  • The comma method should only be used if you need a quick solution.
Hiring Now
Capital One
Fintech • Machine Learning • Payments • Software • Financial Services
SHARE