re.findall字符串。在同一命令中对字符串进行轻微修改?

时间:2017-07-25 08:15:41

标签: python regex string

我正在使用Python 3.6。我目前正在read.txt文件中搜索一个字符串。但是,有没有办法对该字符串进行轻微修改?我举例说明我的代码:

lines = [] # create an empty list
str1 = "does not include a report on internal controls"
with open(read.txt, 'r') as f:
  line2 = f.read()
  var1 = re.findall(str1, line2, re.I) # find str1 or str2 in read.txt
  if len(var1) > 0:
     lines.append('1') # if it exists, append a 1 to the list "lines"
  else:
     lines.append('0') # otherwise a 0

我的问题是,我可以在str1中轻松更改介词吗?我还想搜索“不包含 内部控件”(“of”而不是“on”)。可能是将字符串拆分为两个并允许re.findall命令行中的“on / of”?不知道怎么做......有什么建议吗?

非常感谢你的时间! 最好,

1 个答案:

答案 0 :(得分:1)

您可以使用替换:

str1 = r"does not include a report (on|of) internal controls"

请参阅演示:https://regex101.com/r/Z5qTl4/1

正如@WiktorStribiżew建议的那样(请参阅评论),在这种情况下,您可以将替换(on|of)替换为o[nf]