gpt4 book ai didi

python - 选择性 python 字符串替换

转载 作者:行者123 更新时间:2023-11-30 23:41:31 26 4
gpt4 key购买 nike

我正在尝试替换 pimath.pi使用以下 Python 函数。

def cleanup(x):
return x.replace("pi", "math.pi")

我有以下字符串:

a = "2*pi"
b = "the pink elephant"

cleanup(a) 的输出是:2*math.pi -- 这很好用!

cleanup(b) 的输出是 the math.pink elephant -- 问题:我不想改变“文本”。

有人可以帮助我吗?

最佳答案

您正在寻找正则表达式,特别是“单词边界”(\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 - 选择性 python 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11967379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com