在Python中对捕获的组进行字符串操作

时间:2018-06-23 07:33:11

标签: python regex

我有一个字符串:

str1 = "abc = def"

我想将其转换为:

str2 = "abc = #Abc#"

我正在尝试:

re.sub("(\w+) = (\w+)",r"\1 = %s" % ("#"+str(r"\1").title()+"#"),str1)

但它返回:(未完成字符串操作)

"abc = #abc#"
  • .title()不起作用的可能原因是什么??
  • 如何在python中对捕获的组使用字符串操作?

2 个答案:

答案 0 :(得分:6)

借助一个小功能,您可以看到发生了什么:

import re

str1 = "abc = def"

def fun(m):
    print("In fun(): " + m)
    return m

str2 = re.sub(r"(\w+) = (\w+)",
    r"\1 = %s" % ("#" + fun(r"\1") + "#"),
    #                   ^^^^^^^^^^
    str1)

哪个产量

In fun(): \1

因此,您基本上想做的是将\1(不是替代品!)变成大写版本,显然仍然保留\1。与您对\1的调用相比,str.title()仅用捕获的内容以后替换。

使用@Rakesh建议的lambda函数。

答案 1 :(得分:5)

尝试使用lambda

例如:

import re
str1 = "abc = def"
print( re.sub("(?P<one>(\w+)) = (\w+)",lambda match: r'{0} = #{1}#'.format(match.group('one'), match.group('one').title()), str1) )

输出:

abc = #Abc#
相关问题