put variable in regex pattern in Python Example

Example 1

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']

 

Example 2

import re

txt = "Hello Python"

# My variable
var = "Python"

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

# Result
print(r)

Output:

[' Python']

Example 3

import re

txt = "Hello Python"

# My variable
var = "Python"

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

# Result
print(r)

Output:

[' Python']

 

Example 3

import re

txt = "Hello Python"

# My variable
var = "Python"

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

# Result
print(r)

Output:

[' Python']