[Tutor] How to find a word in a string
Mats Wichmann
mats at wichmann.us
Mon May 3 21:20:29 EDT 2021
On 5/3/21 7:09 PM, Phil wrote:
> This is a bit trickier that I had at first thought, for example:
>
> test = 'Do this, then do that.'
>
> if 'this' in test.lower().split():
> print('found')
> else:
> print('not found')
>
> Does not find 'this' because of the comma.
>
> I had experimented with .find() but that's not the answer either because
> if I was searching a sentence for 'is' it would be found in 'this'
> rather than only 'is' as a word. I also thought about striping all
> punctuation but that seems to be unnecessarily complicated.
>
> So, how I might I deal with the comma in this case?
>
Depends on your requirements, which seem to be more complex...
without getting too fussy:
if 'this' in test:
beyond that, you're getting into the range of regular expressions, which
we usually tell people "don't reach for them until you need to", but it
does seem like your whole-word requirement means you may need to...
More information about the Tutor
mailing list