I am trying to replace the pi with math.pi using the following Python function.
def cleanup(x):
return x.replace("pi", "math.pi")
I have the following strings:
a = "2*pi"
b = "the pink elephant"
The output for cleanup(a) is: 2*math.pi — This works well!
The output for cleanup(b) is the math.pink elephant — problem: I don’t want “text” to change.
Can someone help me?
You’re looking for regular expressions, particularly, the “word boundary” (
\b) assertion: