潜艇表现出不寻常的行为

2024-09-27 22:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

import re
value_list = ['oper-status','downward','upward','some','mid']
regex = r"\$\d+"
test_str = "Test Succeeded!! value is within the range of $1-$2 ,$3 $4 its value is {{post['x']}}"

matches = re.finditer(regex, test_str)
i = 0
if len(value_list) > 1 :
  for matchNum, match in enumerate(matches):
        matchNum = matchNum + 1
        i = i + 1
        print ("{match}".format( match = match.group()))
        test_str = re.sub(regex,value_list[i],test_str,count=i)
   print test_str

我得到以下输出

$1  
$2
$3
$4
Test Succeeded!! value is within the range of downward-upward ,upward some its value is {{post['x']}}

在我期待的时候

Test Succeeded!! value is within the range of downward-upward ,some mid its value is {{post['x']}}

我的代码有什么问题


Tags: thetestreisvaluematchsomelist
3条回答

因为您使用的是count=i,所以字符串将被替换为:

i=1->"Test Succeeded!! value is within the range of downward-$2 ,$3 $4 its value is {{post['x']}}"

i=2->"Test Succeeded!! value is within the range of downward-upward ,upward $4 its value is {{post['x']}}"

i=3->"Test Succeeded!! value is within the range of downward-upward ,upward some its value is {{post['x']}}"

您应该改用count=1

这是因为在re.sub中指定count=i而不是count=1

  • 在第一次迭代中,i=1,$1被替换
  • 在第二次迭代中,i=2,$2$3被替换
  • 在第3次迭代中,i=3,$4被替换
  • 在第4次迭代中,i=4,没有什么可以替换的了

你可以用str.format来完成所有这些

value_list = ['oper-status','downward','upward','some','mid']
test_str = "Test Succeeded!! value is within the range of {x[1]}-{x[2]} ,{x[3]} {x[4]} its value is {{post['x']}}".format(x=value_list)
# "Test Succeeded!! value is within the range of downward-upward ,some mid its value is {post['x']}"

通过在lambda表达式中将组1值转换为int来访问列表中的替换字符串时,直接将re.sub\$(\d+)正则表达式一起使用:

import re
value_list = ['oper-status','downward','upward','some','mid']
regex = r"\$(\d+)"
test_str = "Test Succeeded!! value is within the range of $1-$2 ,$3 $4 its value is {{post['x']}}"
print re.sub(regex,lambda x: value_list[int(x.group(1))], test_str)

参见Python demo

这个一次性的regex替换将帮助您避免与原始方法类似的问题,也就是说,您用count=i替换的次数超过了必要的次数

如果可以有$12(并且列表没有12个元素)这样的匹配项,请添加一个条件:

print(re.sub(regex,lambda x: value_list[int(x.group(1))] if int(x.group(1)) < len(value_list) else x.group(), test_str))

this Python demo

相关问题 更多 >

    热门问题