How to search for words in a string with Python (substring)
In this article you will learn how to search for words in a string with Python, in a simple way using Python methods.
What’s up programmer, all right? Let’s learn more about Python!
The easiest way to check if a string contains any words in Python is to use “in”
This way we can make a conditional “in” our program, check it out:
phrase = 'O rato roeu a roupa do rei de Roma' if 'rato' in phrase: print("Found!")
Just make sure that when using this method the variable you are looking for something, in our case phrase, contain some value and be a string, otherwise your program will generate an error
Tip: You can leave the negative sentence using “not” in instead of ”in”
Another way we have to find strings in a string in Python is with the “find” method
Check out this example:
phrase = 'O rato roeu a roupa do rei de Roma' if phrase.find('rato'): print("Found!")
In these two ways you can scan a string looking for a particular word.
Or as “substring methods” that’s how they are commonly Known as
Regarding performance, the “in” method comes out ahead of the “find” method
So prefer using it instead of using “find” in your software
In this article we learned how to search for words in a string with Python
First we use “in”, which checks if a string is “in another string”
Then we learned a variation with the” find” method, which returns us in the same way looking for a certain string in another sentence.
Want to learn more about Python? Click here!