Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python 3.5, how do I compare a string variable with part of another string? [duplicate]

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")
like image 620
python_learner Avatar asked May 12 '16 16:05

python_learner


People also ask

How do you compare parts of a string with another string in Python?

Use the in operator for partial matches, i.e., whether one string contains the other string. x in y returns True if x is contained in y ( x is a substring of y ), and False if it is not. If each character of x is contained in y discretely, False is returned.

How do you get a specific part of a string in Python?

Python provides different ways and methods to generate a substring, to check if a substring is present, to get the index of a substring, and more. start - The starting index of the substring. stop - The final index of a substring. step - A number specifying the step of the slicing.

How do I compare the contents of two strings in Python?

String Equals Check in Python In python programming we can check whether strings are equal or not using the “==” or by using the “. __eq__” function. Example: s1 = 'String' s2 = 'String' s3 = 'string' # case sensitive equals check if s1 == s2: print('s1 and s2 are equal.

How do you check a string contains a substring in Python?

To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")


1 Answers

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.

like image 125
John Coleman Avatar answered Oct 03 '22 11:10

John Coleman