【问题标题】:Python replace string pattern with output of functionPython用函数的输出替换字符串模式
【发布时间】:2012-09-17 19:43:15
【问题描述】:

我在 Python 中有一个字符串,比如The quick @red fox jumps over the @lame brown dog.

我正在尝试将每个以 @ 开头的单词替换为将单词作为参数的函数的输出。

def my_replace(match):
    return match + str(match.index('e'))

#Psuedo-code

string = "The quick @red fox jumps over the @lame brown dog."
string.replace('@%match', my_replace(match))

# Result
"The quick @red2 fox jumps over the @lame4 brown dog."

有没有聪明的方法来做到这一点?

【问题讨论】:

  • 你所拥有的是好的。你在一个声明中做到这一点。

标签: python regex


【解决方案1】:

试试:

import re

match = re.compile(r"@\w+")
items = re.findall(match, string)
for item in items:
    string = string.replace(item, my_replace(item)

这将允许您用函数的输出替换以 @ 开头的任何内容。 我不太清楚您是否也需要有关该功能的帮助。让我知道是否是这种情况

【讨论】:

  • re.findall(pattern, string) -- 请修复
  • 这实际上非常有用,因为它允许您仅替换字符串中的匹配元素。
【解决方案2】:

您可以将函数传递给re.sub。该函数将接收一个匹配对象作为参数,使用.group() 将匹配项提取为字符串。

>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

【讨论】:

  • 美丽。我不知道我可以将函数传递给 re.sub,但我觉得我应该可以。
【解决方案3】:

一个简短的正则表达式和减少:

>>> import re
>>> pat = r'@\w+'
>>> reduce(lambda s, m: s.replace(m, m + str(m.index('e'))), re.findall(pat, string), string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

【讨论】:

    【解决方案4】:

    我不知道您也可以将函数传递给re.sub()。引用@Janne Karila 的答案来解决我遇到的问题,该方法也适用于多个捕获组。

    import re
    
    def my_replace(match):
        match1 = match.group(1)
        match2 = match.group(2)
        match2 = match2.replace('@', '')
        return u"{0:0.{1}f}".format(float(match1), int(match2))
    
    string = 'The first number is 14.2@1, and the second number is 50.6@4.'
    result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string)
    
    print(result)
    

    输出:

    The first number is 14.2, and the second number is 50.6000.

    这个简单的示例要求所有捕获组都存在(没有可选组)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2014-09-03
      • 2020-05-13
      相关资源
      最近更新 更多