[英]Python regular expression substitution function using lambda in the replacement field
I am trying to mimic 'i am your'.title()
string function with the following code to get the output as I Am Your .我正在尝试使用以下代码模拟'i am your'.title()
字符串函数,以获取输出为I Am Your 。 But it gives the same i am your as output without capitalizing the words但它给出了相同的我是你的输出而不用大写的话
re.sub(r"\b'\w", lambda m: m.group().upper(), 'i am your')
During the process of verfiying it, I came across this following snippet in the internet but not able to comprehend how the lambda gets the input from/as :在验证它的过程中,我在互联网上遇到了以下代码片段,但无法理解 lambda 如何从 /as 获取输入:
re.sub("[ab]", lambda x: x.group(0).upper(), "charly") # chArly
because,因为,
>>> f = lambda x: x.group(0).upper()
>>> f("[ab]")
AttributeError: 'str' object has no attribute 'group'
>>> f(["a","b"])
AttributeError: 'list' object has no attribute 'group'
To understand it better, I tried to decode it with Python disassembler, but still it seems vague为了更好地理解它,我尝试用 Python 反汇编器对其进行解码,但它仍然看起来很模糊
>>> dis.dis('re.sub("[ab]", lambda x: x.group(0).upper(), "charly")')
0 POP_JUMP_IF_FALSE 11877
3 POP_JUMP_IF_TRUE 25205
6 STORE_SLICE+0
7 <34>
8 DELETE_NAME 25185 (25185)
11 FOR_ITER 11298 (to 11312)
14 SLICE+2
15 IMPORT_NAME 28001 (28001)
18 DELETE_GLOBAL 24932 (24932)
21 SLICE+2
22 SETUP_LOOP 8250 (to 8275)
25 SETUP_LOOP 26414 (to 26442)
28 POP_JUMP_IF_FALSE 30063
31 JUMP_IF_TRUE_OR_POP 12328
34 STORE_SLICE+1
35 <46>
36 <117> 28784
39 LOAD_NAME 10354 (10354)
42 STORE_SLICE+1
43 <44>
44 SLICE+2
45 <34>
46 DUP_TOPX 24936
49 POP_JUMP_IF_FALSE 31084
52 <34>
53 STORE_SLICE+1
upper()
to get the first char in caps您需要使用upper()
来获取大写的第一个字符'
between word break and word escape literals, you need to remove that.分词符和单词转义文字之间有一个'
,您需要将其删除。m.group(0)
or m[0]
to get matched string.并且您需要使用m.group(0)
或m[0]
来获取匹配的字符串。>>> re.sub(r"\b\w",lambda m: m[0].upper(),"i am your")
'I Am Your'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.