I want to create code which will return true if the string contains the word "post". So when I give my code string like "postgre", "postgres", "sqlpost" - it will return true. How can I do it?
2 Answers
If you care about matching exactly a word in a more elegant way than if ' post ' in mystring, you can use regex word boundaries which will enforce that your pattern only matches the word itself, not a substring within a word. For example,
>>> re.search(r"\bpost\b", "my post")
<_sre.SRE_Match object at 0x7fcb95165b28>
>>> re.search(r"\bpost\b", "my postgres")
>>>
matches post but not postgres.
if needle in haystack:(for appropriate values ofneedleandhaystack).