1

I am trying to test if some words are in a sentence, as per the code below. Unfortunately the first in I would like to mean:

  • test if the sentence contains x,
  • But I think its taking it as sentence is looping over something.

How does one correct the below code:

Very confused, in a new terminal it works:

Python 3.8.10 (default, Jun  2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> words = ['foo', 'bar']
>>> sentence = 'Some sentence bar the beach'
>>> match = any(x in sentence for x in words)
>>> match
True

But in a pdb it doesnt:

(Pdb) words = ['foo', 'bar']
(Pdb) words
['foo', 'bar']
(Pdb) sentence = 'Some sentence bar the beach'
(Pdb) sentence
'Some sentence bar the beach'
(Pdb) match = any(x in sentence for x in words)
*** NameError: name 'sentence' is not defined
(Pdb)

Okay I see the code is working, but not in the pdb, what is the gotcha with the pdb?

10
  • 2
    Why do you think this is incorrect? Commented Oct 6, 2021 at 16:59
  • Split it by spaces: sentence.split() Commented Oct 6, 2021 at 17:00
  • 1
    Your code looks fine to me. Commented Oct 6, 2021 at 17:01
  • 1
    Hmm, surprising, cause it says for me the equivalent of 'sentence' is not defined (in my real codE) ... okay there must be a difference between my real code and minimum reproducible exmaple, will do some more digging... Commented Oct 6, 2021 at 17:05
  • 1
    Interesting situation. Seems to be answered here: stackoverflow.com/a/48197521/5225301 Commented Oct 6, 2021 at 19:55

1 Answer 1

-1

This will give you a list of all matching words

match = [x for x in words if x in sentence]

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.