'Check if substring with leading and trailing whitespaces is in string

Imagine I need to check if in

longString = "this is a long sting where a lo must be detected."

the substring lo as a word is contained. I need to use the leading and trailing whitespace to detect it like " lo ". How do I do this?
(To complicate matters the search string comes from a list of strings like [' lo ','bar'].I know the solution without whitespaces like this. )



Solution 1:[1]

You can use regex....

import re

seq = ["  lo  ", "bar"]
pattern = re.compile(r"^\s*?lo\s*?$")
for i in seq:
    result = pattern.search(i)
    if result:                  #  does match
        ... do something
    else:                       #  does not match
        continue

Solution 2:[2]

why don't you clean your string to remove whitespace before you start to check if your match is in your string so that you don't have to deal this case?

do thing like

" lo " .strip() become 'lo'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alexpdev
Solution 2 paulyang0125