Check if substring with leading and trailing whitespaces is in string

Viewed 75

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. )

2 Answers

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

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'

Related