我需要一个小的帮助,以便使用python从记事本中仅过滤所需的行
示例:
输入
- A MY NAME IS ANDY
- B MY NAME IS BANDY
- C MY NAME IS CANDY
- A MY NAME IS ANTRO
- B MY NAME IS BANTRO
- C MY NAME IS CANTRO
仅搜索第一个字符串并检查它是否为B,它将打印相应的行
输出
- B MY NAME IS BANDY
- B MY NAME IS BANTRO
答案 0 :(得分:0)
有多种方法。假设数据存储在名为.txt的文件中,则可以使用
读取该文件with open('sample.txt') as f:
lines = f.read().splitlines()
然后使用startswith方法过滤并打印结果
filtered_list = [x for x in lines if x.startswith('- B')]
for item in filtered_list:
print(item)
导致
- B MY NAME IS BANDY
- B MY NAME IS BANTRO