7

I'm currently learning Python and I have a question which I cannot find the answer too, currently I am trying to take a string variable given from the user and comparing it to part of another string. I want something like this:

Program: The given sentence is "I like chemistry", enter a word in the sentence given.

User: like

Program: Your word is in the sentence.

I can only seem to make a program using the if function and == but this only seems to recognize that the two strings are similar if I type the full sentence given by the program.

From the some of the answers I have changed my program to but there seems to be an error I cannot find.

sentence=("I like chemistry")
print("The given sentence is: ",sentence)
word=input("Give a word in the sentence: ").upper
while word not in sentence:
    word=input("Give a valid word in the sentence: ")
if word in sentence:
    print("valid")
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

4 Answers4

1

You could use in together with split:

>>> s = "I like chemistry"
>>> words = s.split()
>>> "like" in words
True
>>> "hate" in words
False

The difference between this approach vs. using in against the non-split string is like this:

>>> "mist" in s
True
>>> "mist" in words
False

If you want arbitrary substrings then use simply w in s but is you want white-space delimited words then use w in words.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
0
if word in sentence:

Welcome to the wonderful world of python.

polku
  • 1,575
  • 2
  • 14
  • 11
0

In Python you use if substring in string: ....

Example:

mystring = "I like chemistry"
if "like" in mystring:
    print("Word is in sentence")
else:
    print("Word is not in sentence")

Hope this helps!

linusg
  • 6,289
  • 4
  • 28
  • 78
0

Instead of thinking it as finding a substring, think it as checking membership. And all sequence types in Python expose the same interface for that purpose. Say s is a sequence, i.e str, list, tuple and to see if m is in s,

>>> m in s # => bool :: True | False

The same in operator works for dict keys and set as well, though they are not sequences.

C Panda
  • 3,297
  • 2
  • 11
  • 11