1

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

Fred
  • 417
  • 5
  • 16

2 Answers2

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
Alexander
  • 16,091
  • 5
  • 13
  • 29
  • 1
    Yes, I went this way even avoiding the whitespaces rewriting the lookup list as `(\blo\b|bar)`. – Fred May 14 '22 at 11:28
0

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'

paulyang0125
  • 307
  • 2
  • 7
  • 1
    Then it would match "long", too. But it should math the word lo only. All items in the list are allowed to match anywhere in the searchstring. – Fred May 14 '22 at 11:00