对字符串re.findall python3稍作修改

时间:2017-07-26 15:37:39

标签: python string parsing

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

lines = [] # create an empty list
str1 = "as a result, we will comply with such standard"
with open(read.txt, 'r') as f:
  line2 = f.read()
  var1 = re.findall(str1, line2, re.I) # find str1 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

我的问题是我想要" re.findall"函数也看同一个str1但没有"将"紧张。这也是看str1' ="因此,我们遵守这样的标准"。任何建议将不胜感激!

感谢您的时间,

1 个答案:

答案 0 :(得分:2)

In [29]: str1 = "as a result, we (will ){0,1}comply with such standard"

In [30]: re.search(str1, str2)
Out[30]: <_sre.SRE_Match object; span=(0, 46), match='as a result, we will comply with such standard'>

In [31]: re.search(str1, str3)
Out[31]: <_sre.SRE_Match object; span=(0, 41), match='as a result, we comply with such standard'>

如果将“will”放在括号中并添加{0,1},它将找到该子句存在0或1次的所有实例。您在问题标题中提到了re.search,但代码使用的是re.findall。我猜你想要搜索。

re.searchre.findall之间的差异:

In [38]: re.search(str1, str2).group()
Out[38]: 'as a result, we will comply with such standard'


In [38]: re.search(str1, str2).group()
Out[38]: 'as a result, we will comply with such standard'

In [39]: re.findall(str1, "not in this string")
Out[39]: []

In [40]: re.findall(str1, str2)
Out[40]: ['will ']

由于空列表的计算结果为False,您的代码将起作用。见:

In [41]: bool(['will '])
Out[41]: True

In [42]: bool([])
Out[42]: False