I would like to split a string by a variable and a character but it doesn't use the variable

Question:

I used re.split to be able to split it with more than 1 character and it works fine for the ", " but it doesn’t seem to be detecting the variable.

import re

a1 = "my"
b2 = "Hello! 34 is my number, bye."
b2 = re.split("{a1}|, ", b2)
print(b2)

I tried changing it to different variable types but that’s not it. I don’t know if it’s the "|" but I can’t figure out why it’s happening.

Asked By: rjerhwhrwh

||

Answers:

You have given a literal string {a1} to the regex, so it would split on the 4 chars bracket/’a’/’1’/bracket, you need a f-string to use the value of the variable

a1 = "my"
b2 = "Hello! 34 is my number, bye."

b2 = re.split(f"{a1}|, ", b2)
print(b2) # ['Hello! 34 is ', ' number', 'bye.']

print("{a1}|, ")  # {a1}|, 
print(f"{a1}|, ") # my|,
Answered By: azro

If you want a string to use a value from a variable, one convenient way is to use an f string:

b2 = re.split(f"{a1}|, ", b2)

For regex, I also recommend using raw strings, it will save you many headaches with special characters.

b2 = re.split(rf"{a1}|, ", b2)
Answered By: Gulzar