Fred
Fred

Reputation: 583

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

Upvotes: 1

Views: 764

Answers (2)

Alexander
Alexander

Reputation: 17291

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

Upvotes: 1

paulyang0125
paulyang0125

Reputation: 337

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'

Upvotes: 0

Related Questions