Python 一行代码实现字符串替换:将句点替换为方括号
使用 Python 正则表达式库 re.sub() 和匿名函数 lambda,仅需一行代码即可将字符串中的句点 (.) 替换为方括号 ([.]):
re.sub(pattern, lambda match: match.group().replace('.', '[.]'), text)
代码解释:
re.sub(pattern, repl, string):用于在字符串string中使用正则表达式pattern查找匹配项,并使用repl替换它们。lambda match: match.group().replace('.', '[.]'):这是一个匿名函数,它接受一个匹配对象match作为参数。它使用match.group()获取匹配的字符串,然后使用replace('.', '[.]')将句点替换为方括号。
示例:
import re
text = 'This is a sentence. With some dots.'
pattern = r'\.'
result = re.sub(pattern, lambda match: match.group().replace('.', '[.]'), text)
print(result)
输出:
This is a sentence[.] With some dots[.]
注意:
- 在正则表达式中,句点 (.) 是一个特殊字符,它匹配除换行符之外的任何字符。为了匹配句点本身,需要使用转义字符
\。 - 使用方括号 ([.]) 而不是直接使用句点,是为了防止句点被解释为特殊字符。
原文地址: https://www.cveoy.top/t/topic/ovrw 著作权归作者所有。请勿转载和采集!