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")
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.
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.
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.
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!")
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With