Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在尝试使用以下 Python 函数pi替换。math.pi
pi
math.pi
def cleanup(x): return x.replace("pi", "math.pi")
我有以下字符串:
a = "2*pi" b = "the pink elephant"
的输出cleanup(a)是:2*math.pi-- 这很好用!
cleanup(a)
2*math.pi
的输出cleanup(b)是the math.pink elephant-- 问题:我不想改变“文本”。
cleanup(b)
the math.pink elephant
有人能帮我吗?
您正在寻找正则表达式,特别是“单词边界”( \b) 断言:
\b
import re print re.sub(r'\bpi\b', 'math.pi', "2*pi") print re.sub(r'\bpi\b', 'math.pi', "the pink elephant")
听起来你需要一个更复杂的过滤器,你应该看看正则表达式,有一个内置在 Python 中的模块
http://docs.python.org/library/re.html