Python

Substring method in Python – What to use?

March 30, 2022

Substring method in Python – What to use?

In this article we will learn a replacement for the substring method in Python, to search for some text in a string in a simple way

Substring method in Python thumb

Hey you programmer, ok? Let’s learn how to search for texts in strings in Python.

In other languages it is very common to have a method called substring, or something similar

However in Python we do not have a method similar to this, but there are other alternatives

The most used is with the in operator

See this example:

word = 'test'

phrase = 'Does this phrase has a test word?'

if(word in phrase):
 print("Yes, it does!")

This way we can simulate a substring,

 because “in” checks the incidence of a string x on another y

We can thus easily identify a word in the middle of a sentence, as shown in the example

Which is totally related to this string and substring search topic, enjoy!

There we will use the find method, which is similar to the “in” operator, but it is a Python function

Conclusion

We can use the” in” operator to replace the substring method in Python, as it doesn’t exist

But we were able to copy its functionality successfully without any difference

Identifying if a string exists in another one, in a simple way

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x