【问题标题】:Python command/package for researching substrings? [closed]用于研究子字符串的 Python 命令/包? [关闭]
【发布时间】:2021-09-05 03:10:02
【问题描述】:

有谁知道如何在 Python 中做类似 Bash'seq 的操作?

例如,我想搜索文档中包含字符链“measurement = abc”的行并将“abc”替换为我自己的内容(使用"{}".format()或类似的东西)。

我是否需要使用迭代循环检查文档中的每个字符串/子字符串,或者是否有 Python 中的内置命令或包已经这样做了?

谢谢!

【问题讨论】:

    标签: python string replace


    【解决方案1】:

    我会使用 Python 中的正则表达式实现(内置 re 模块)。

    这可以通过positive lookbehind assertion 来完成。

    (?

    import re
    
    data = "measurement = abc some other text measurement = abc some other text"
    
    data = re.sub(r'(?<=measurement\s=\s)abc', '123', data) # positive lookbehind assertion
    
    print(data)  # "measurement = 123 some other text measurement = 123 some other text"
    

    【讨论】:

    • 谢谢@ChrisOram,它似乎正在工作。我会尝试摆弄 re 包,因为它看起来真的很强大。
    • 很好,很高兴听到这个消息。
    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多