检查字符串是否以 Python 中的几个子字符串之一开头
Check if string begins with one of several substrings in Python
我不知道如何为一组子字符串执行 line.startswith("substring")
,所以我尝试了底部代码的一些变体:因为我有已知的 4 字符开头子字符串的奢侈,但我很确定我的语法有误,因为这不会拒绝任何行。
(上下文:我的目标是在读取文件时丢弃 header 行。Header 行以一组有限的字符串开头,但我不能只检查子字符串任何地方,因为有效的内容行后面可能会在字符串中包含关键字。)
cleanLines = []
line = "sample input here"
if not line[0:3] in ["node", "path", "Path"]: #skip standard headers
cleanLines.append(line)
您的问题源于以下事实:字符串切片不包括停止索引:
In [7]: line = '0123456789'
In [8]: line[0:3]
Out[8]: '012'
In [9]: line[0:4]
Out[9]: '0123'
In [10]: line[:3]
Out[10]: '012'
In [11]: line[:4]
Out[11]: '0123'
在 i
和 j
之间分割字符串 returns 子字符串从 i
开始,到(但不包括)j
结束。
只是为了让您的代码 运行 更快,您可能想要测试集合中的成员资格,而不是列表中的成员资格:
cleanLines = []
line = "sample input here"
blacklist = set(["node", "path", "Path"])
if line[:4] not in blacklist: #skip standard headers
cleanLines.append(line)
现在,您实际使用该代码所做的是 startswith
,它不受任何长度参数的限制:
In [12]: line = '0123456789'
In [13]: line.startswith('0')
Out[13]: True
In [14]: line.startswith('0123')
Out[14]: True
In [15]: line.startswith('03')
Out[15]: False
所以你可以这样做来排除 headers:
cleanLines = []
line = "sample input here"
headers = ["node", "path", "Path"]
if not any(line.startswith(header) for header in headers) : #skip standard headers
cleanLines.append(line)
我不知道如何为一组子字符串执行 line.startswith("substring")
,所以我尝试了底部代码的一些变体:因为我有已知的 4 字符开头子字符串的奢侈,但我很确定我的语法有误,因为这不会拒绝任何行。
(上下文:我的目标是在读取文件时丢弃 header 行。Header 行以一组有限的字符串开头,但我不能只检查子字符串任何地方,因为有效的内容行后面可能会在字符串中包含关键字。)
cleanLines = []
line = "sample input here"
if not line[0:3] in ["node", "path", "Path"]: #skip standard headers
cleanLines.append(line)
您的问题源于以下事实:字符串切片不包括停止索引:
In [7]: line = '0123456789'
In [8]: line[0:3]
Out[8]: '012'
In [9]: line[0:4]
Out[9]: '0123'
In [10]: line[:3]
Out[10]: '012'
In [11]: line[:4]
Out[11]: '0123'
在 i
和 j
之间分割字符串 returns 子字符串从 i
开始,到(但不包括)j
结束。
只是为了让您的代码 运行 更快,您可能想要测试集合中的成员资格,而不是列表中的成员资格:
cleanLines = []
line = "sample input here"
blacklist = set(["node", "path", "Path"])
if line[:4] not in blacklist: #skip standard headers
cleanLines.append(line)
现在,您实际使用该代码所做的是 startswith
,它不受任何长度参数的限制:
In [12]: line = '0123456789'
In [13]: line.startswith('0')
Out[13]: True
In [14]: line.startswith('0123')
Out[14]: True
In [15]: line.startswith('03')
Out[15]: False
所以你可以这样做来排除 headers:
cleanLines = []
line = "sample input here"
headers = ["node", "path", "Path"]
if not any(line.startswith(header) for header in headers) : #skip standard headers
cleanLines.append(line)