如何使用Python在文件中精确长度搜索字符串

2024-06-16 11:09:55 发布

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

我有文件包含

google 
google talk browser
google talks
google talk

如何使用python搜索文件中的“talks”,并且在不使用额外字符串的情况下精确搜索并使用python打印行


Tags: 文件字符串browsergoogle情况talktalks
2条回答
import re

txt = open("youfile.txt").read()
if re.search(r'[^\s]?google talk[\s$]?',txt):
    //code for string present
else:
    //code for string not-present

只需使用比较运算符:

with open('file.txt', 'r') as handle:
    for index, line in enumerate(handle, 1):
        if line.strip() == 'google talk':
            print 'Match found on line', index

相关问题 更多 >