Python efficient way to check if very large string contains a substring

后端 未结 8 1766
無奈伤痛
無奈伤痛 2021-01-02 05:04

Python is not my best language, and so I\'m not all that good at finding the most efficient solutions to some of my problems. I have a very large string (coming from a 30 MB

8条回答
  •  执笔经年
    2021-01-02 05:43

    Are you implying that only a complete line will match? (your EDIT: matching on a newline only example seems to)

    Then I imagine

    for line in open('file').readlines():
      if line==small_string:
        return True
    return False
    

    IE, using == is quicker than 'in' - perhaps. I wouldn't be surprised if the underlying implementation of in catches the case where the line to search and the string to search for are the same length and just attempts an == itself.

    woudl be better.

提交回复
热议问题