【问题标题】:Selective python string replacements选择性python字符串替换
【发布时间】:2012-08-11 15:14:01
【问题描述】:

我正在尝试使用以下 Python 函数将 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(b) 的输出是 the math.pink elephant -- 问题:我不想改变“文本”。

有人可以帮我吗?

【问题讨论】:

  • 如果您正在修复 Python 代码,只需定义“from math import pi”,您无需替换任何内容。现在 Python 允许 Unicode 标识符,您还可以将此导入添加到您的代码中:from math import pi as π 然后您可以编写类似 'C = π*D' 的代码

标签: python string function replace pi


【解决方案1】:

听起来你需要一个更复杂的过滤器,你应该研究正则表达式,Python 中内置了一个模块

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

【讨论】:

    【解决方案2】:

    您正在寻找正则表达式,尤其是“单词边界”(\b) 断言:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 2020-08-28
    • 2013-01-30
    • 2016-02-25
    • 2020-12-25
    • 2014-08-31
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多