Last modified: Jan 10, 2023 By Alexander Williams

How to put variable in regex pattern in Python

This tutorial will teach four perfect techniques to put a variable in the regex pattern.

Let's get started.

F-string to put a variable in regex pattern

f-string is a new python syntax available on Python >= 3.6.

We'll see how to put a variable in regex using f-string in the following example:

import re

txt = "Hello Python"

# My variable
var = "Python"

# Regex with f-string
r = re.findall(f"\s{var}", txt)

# Result
print(r)

Output:

[' Python']

As you can see, the method works perfectly.

format() to put a variable in regex pattern

format() is a built-in function that can put a variable or more into a string.

Let's see an example:

import re

txt = "Hello Python"

# My variable
var = "Python"

# Regex with format()
r = re.findall("\s{}".format(var), txt)

# Result
print(r)

Output:

[' Python']

%s symbol to put a variable in regex pattern

We can also use the %s symbol to put a variable in the regex pattern. Let's see how to use it in an example.

import re

txt = "Hello Python"

# My variable
var = "Python"

# Regex with % symbol
r = re.findall("\s%s"%var, txt)

# Result
print(r)

Output:

[' Python']

For more information about the %s symbol, I suggest you read What Does %s Mean in Python?

+ operator to put a variable in regex pattern

The + operator can be used to concatenate strings. We'll use this operator to join the regex pattern with the variable in our situation.

import re

txt = "Hello Python"

# My variable
var = "Python"

# Regex with + symbol
r = re.findall("\s" + var, txt)

# Result
print(r)

Output:

[' Python']