搜索确切字符串的正确命令是什么,

发布于 2024-08-13 20:21:15 字数 103 浏览 1 评论 0原文

我尝试过startswith、find、re.sub,但似乎都是找到与其部分匹配的字符串。 iam 寻找命令,该命令搜索 iam 在给定文件中搜索的确切字符串。

感谢您的帮助。

i have tried startswith , find , re.sub but all seems to be find that string that matches part of it . iam looking for command which searchs the exact string which iam searching for in a given file.

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

另类 2024-08-20 20:21:15

我猜测您要问什么,但我认为您想要的是在文件中找到精确的文本行。如果是这种情况,有几种方法可以做到这一点。

使用正则表达式来匹配行的开头和结尾:

regex = re.compile("^whatevermystringis$", re.M)
match = regex.search(open(filename).read())
match.span()

使用直接 Python 查找行:(

line_to_find = "blah, blah, blah\n"
for line_num, line in enumerate(open(filename)):
    if line == line_to_find:
        print line_num

小心处理行结尾。)

同样,这是对您想要询问的内容的猜测。

I'm guessing as to what you're asking about, but I think what you're wanting is to find an exact line of text in a file. If that's the case, there are a couple of ways to do it.

Use a regex to match start and end of line:

regex = re.compile("^whatevermystringis$", re.M)
match = regex.search(open(filename).read())
match.span()

Find the line using straight Python:

line_to_find = "blah, blah, blah\n"
for line_num, line in enumerate(open(filename)):
    if line == line_to_find:
        print line_num

(Take care in handling your line endings.)

Again, this is a guess as to what you're trying to ask.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文