简体   繁体   中英

Selective python string replacements

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:

import re
print re.sub(r'\bpi\b', 'math.pi', "2*pi")
print re.sub(r'\bpi\b', 'math.pi', "the pink elephant")

Sounds like you need a more sophisticated filter, you should look into regular expressions, there is a module for it built-in into Python

http://docs.python.org/library/re.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM