Python用函数的输出替换字符串模式
我在Python中有一个字符串,比如说Python用函数的输出替换字符串模式,python,regex,Python,Regex,我在Python中有一个字符串,比如说敏捷的@redfox跳过了@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',
敏捷的@redfox跳过了@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."
有什么聪明的方法可以做到这一点吗?试试:
import re
match = re.compile(r"@\w+")
items = re.findall(match, string)
for item in items:
string = string.replace(item, my_replace(item)
这将允许您用函数的任何输出替换以@开头的任何内容。
我不太清楚你是否也需要这个功能的帮助。如果是这种情况,请告诉我您是否可以将函数传递给。函数将接收匹配对象作为参数,使用
.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.'
带有regex和reduce的简短示例:
>>> 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.'
我也不知道您可以将函数传递给
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)
输出:
第一个数字是14.2,第二个数字是50.6000。
这个简单的示例要求所有捕获组都存在(没有可选组)。您拥有的很好。你用一句话就做到了,很漂亮。我不知道我可以将函数传递给re.sub,但我觉得我应该能够。
re.findall(pattern,string)
——请修复这实际上非常有用,因为它允许您只替换字符串中匹配的元素。