A string is a collection of Characters and in Python, creating and manipulating a string is very easy as compared to other programming languages. Python also provides us with many string methods that can be used to perform various operations on a string.
While learning the Python string topic, you will defiantly come across a general problem of finding a particular piece of string present in a longer string. This problem state that we have two strings One is the main string, and the other is the substring, and using the code, we have to create a program that can tell whether the substring is present in the main string or not. Here we have provided different ways to solve this problem:
Python in Operator
With the help of Python in operator, we can find whether a piece of string is present in another string or not, in is a list operator, which is generally used to tell that a specific element is present in the list or not.
Example:
Output:
Using find() Method:
The find() method is used to find the index value of a particular element present in the list or string. If the element is present in the list, the find() method returns its index value, else it returns a negative number -1.
Example:
Output:
Using index() Method:
The index() method is used to tell the index value of a specific element present in the list or string. It is similar to the find() method, but if the index() method does not find the element in the string, it throws an error, or else it returns the beginning index value of the element.
Example
Output
Using Python Regular Expression
Regular Expression is used to find the pattern in a string, and they provide a more flexible and efficient way to find a substring from a string. With regular expression, we have many string operations that we can perform on a string.
Example
Output
Using Logical Code
It might be possible you have asked to implement a logic to solve this problem rather than using the special Python methods. Here we have also provided a logic to solve this problem using python code:
Example
Output
Conclusion
The logic we have used in the last example is applicable to every programming language. In competitive programming, we often encounter such kind of problem where we are restricted to using some of the inbuilt functions or methods there we need to implement logic using the basic programming data structure and syntax.
People are also reading:
- Python Program to Find the Sum of Natural Numbers
- WAP to print the truth table for XY+Z
- WAP to calculate the sum of two numbers
- WAP to print the ASCII value of a character
- Python Program to Illustrate Different Set Operations
- WAP to display a message on screen
- Python Program to Find Factorial of Number Using Recursion
- WAP to find the divisors of a positive Integer
Leave a Comment on this Post