[Tutor] How to find a word in a string
Peter Otten
__peter__ at web.de
Tue May 4 03:51:55 EDT 2021
On 04/05/2021 03:09, 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?
If you want to avoid regular expressions you can replace punctuation
with spaces before splitting.
The obvious way would be
test.replace(".", " ").replace(",", " ").replace(...
but there's also str.translate() to deal with multiple (character)
replacements simultaneously:
>>> punct = ",;:.!"
>>> clean = str.maketrans(punct, " " * len(punct))
>>> test = "Do this, then do that."
>>> test.translate(clean)
'Do this then do that '
>>> if "this"in test.translate(clean).lower().split():
print("found")
found
There are still problems like the "-" which may or may not be part of a
word.
More information about the Tutor
mailing list