gpt4 book ai didi

python - 替换 Python 中的前导文本

转载 作者:行者123 更新时间:2023-12-01 06:13:14 26 4
gpt4 key购买 nike

我使用Python 2.6,我想用另一个字符或字符串替换字符串中某些前导字符的每个实例(在我的例子中为 ._$ )。由于在我的情况下替换字符串是相同的,所以我想出了这个:

def replaceLeadingCharacters(string, old, new = ''):
t = string.lstrip(old)

return new * (len(string) - len(t)) + t

这似乎工作正常:

>>> replaceLeadingCharacters('._.!$XXX$._', '._$', 'Y')
'YYY!$XXX$._'
  • 是否有更好(更简单或更有效)的方法可以在 Python 中实现相同的效果?

  • 有没有办法用字符串而不是字符来达到这种效果?像 str.replace() 这样的东西一旦输入字符串中出现与要替换的字符串不同的内容就会停止?现在我想出了这个:

    def replaceLeadingString(string, old, new = ''):
    n = 0
    o = 0
    s = len(old)

    while string.startswith(old, o):
    n += 1
    o += s

    return new * n + string[o:]

    我希望有一种方法可以在没有显式循环的情况下做到这一点

编辑:

使用re有很多答案模块。我有几个问题:

  • 是不是比 str 慢很多?方法何时用作它们的替代品?

  • 是否有一种简单的方法可以正确引用/转义将在正则表达式中使用的字符串?例如,如果我想使用 re对于 replaceLeadingCharacters ,我如何确保 old 的内容变量不会把 ^[old]+ 中的事情弄乱?我宁愿有一个“黑匣子”功能,不需要用户注意他们提供的字符列表。

最佳答案

你的replaceLeadingCharacters()看起来很好。

这里是使用 rereplaceLeadingString() 实现模块(没有 while 循环):

#!/usr/bin/env python
import re

def lreplace(s, old, new):
"""Return a copy of string `s` with leading occurrences of
substring `old` replaced by `new`.

>>> lreplace('abcabcdefabc', 'abc', 'X')
'XXdefabc'
>>> lreplace('_abc', 'abc', 'X')
'_abc'
"""
return re.sub(r'^(?:%s)+' % re.escape(old),
lambda m: new * (m.end() / len(old)),
s)

Isn't it significantly slower than the str methods when used as a replacement for them?

别猜。测量它的预期输入。

Is there an easy way to properly quote/escape strings that will be used in a regular expression?

re.escape()

关于python - 替换 Python 中的前导文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4649997/

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