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

后端 未结 8 1845
無奈伤痛
無奈伤痛 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:50

    I would rely on fast implementation by someone else:

    import subprocess
    from subprocess import STDOUT
    import os
    
    ...
    with open(os.devnull, 'w') as devnull:
        if subprocess.call('grep %s "%s"' % (smallstring, file), shell=True, stdout=devnull, stderr=STDOUT) == 0:
            pass #do stuff
    

    Won't work on windows.

    edit: I'm worried taht grep returns 0 wheter it finds something or not. But I don't have any shell available to me now so I can't test it.

提交回复
热议问题