Python find substring in string + Examples

In this Python tutorial, we will discuss everything on Python find substring in string with a few more examples. We will see, how to find substring from a string in Python.

  • How to find substring in a string
  • How to find substring from string using Python string find() method
  • Check if a string contains a substring in Python
  • How to Count substring in string python using count() method
  • Check if a substring in a string in Python
  • Python split string with multiple delimiters
  • Python split string to substring using split() method
  • Python string startswith substring
  • Extract number from string in Python
  • Check if a string contains a word in python
  • How to find longest palindromic substring in Python
  • Find last index of a string in Python
  • How to check if a python string contains another string

Python find substring in a string

Let us see how to find substring in a string.

  • In Python, we can find a substring from a string using string slicing in python. The slicing starts with the start position and ends at the end position index.
  • To substring any string, We can use slicing which will substring the string.
  • It can take any string as an input and it will produce a substring as an output.

Example:

  • First of all, We need to take a string as a value. In the below python code, You can see, I have taken the value as “Welcome to Python Guide”.
  • Then we need to store the string value in some variable “value”.
  • Now print the “text” and it will give the required substring.

Code for Python string substring

Below represents the code for python substring.

value = 'Welcome to Python Guide'
text = value[18:]
print(text)

Here,

  • Start- The starting index of the substring and the character present in the index is known as substring. If we don’t mention the start, then it is assumed equal to 0. In the above code, I have taken 18 as a start point.
  • end- It is known as terminating index of the substring. If the end is not included, or the specified value exceeds the string length, it is assumed to be equal to the length by default. Here in the above code i have not taken the end, So by default it will take the end value.

After writing the above Python code ( string substring), Ones you will print “text” then the output will appear as a “Guide” as we have taken index from 18 to last index so, We got the last 5 character of string.

Also, you can refer to the below screenshot.

Python find substring in string
Python find substring in string

This is how to find a substring from a string in Python.

Read: Slicing string in Python + Examples

Find substring from string using Python string find() method

  • By using the Python find() method we can find the first occurrence of the specified substring value in a string. If the find() method returns -1 then the value is not present in the string.
  • To find any substring value from the string we have a built-in find() which will find the specific value.
  • The function can take any string as an input and it can produce an integer value as an output.

Example:

  • First of all, We need to take a string value. In the below python code, You can see, I have taken the value as “Python is easy”.
  • Then we need to store the specified substring value in some variable “a”.
  • Now print the “a” and it will give you the integer value of that index.

Check out Python program to reverse a string with examples.

Code for python string find()

Follow the below code to find substring of a string using the Python string find() method.

msg = 'Python is easy'
a = msg.find("easy")
print(a)
  • After writing the above Python code (string find), Ones you will print “a” then the output will appear as a “10” as we want to find the easy from the string. So, here index 10 is the integer value as an output. Also, you can refer to the below screenshot.
Python find substring in string
Python string find()

This is how to find substring from string using Python string find() method.

Read: Could not convert string to float Python

Check if a string contains a substring in Python

  • By using the “in” operator which is used as a comparison operator and also the easiest way to check if a string contains a substring in Python. This operator returns true if the string contains the character, otherwise it returns false.
  • To check whether the string is present or not we use this operator and it will return a boolean value.
  • The function can take any string value as an input and it will return True or False as an output.

Example:

  • First of all, We need to take a string value. In the below python code, You can see, I have taken the value as “Hello John, how are you”.
  • Then we need to store the specified substring value in some variable “store”.
  • Now print the “store” and it will return the value as true or false.

Code for python to check if the string contains substring

Below represents the python code to check if the string contains substring.

msg = "Hello John, how are you"
store = ('how' in msg)
print(store)
  • After writing the above Python code to check(string contains substring), Ones you will print “store” then the output will appear “True” as “how” is present in it. Also, you can refer to the below screenshot.
Python string contains substring
Check if string contains substring
  • If the string does not contains the specified value, then it will return “false” as an output. You can refer to the below screenshot.
Check if a string contains a substring in Python
Check if a string contains a substring in Python

The above code, we can use to check if a string contains a substring in Python. This is an example of how to check if a substring is present in a string in python.

Read: Convert string to float in Python

Count substring in string python using count() method

  • The count() method in Python returns the number of occurrences of a specified substring in the list.
  • To find the occurrence of a specified substring in the given string in Python. We use count() methods which return how many times the substring is present in the string in Python.
  • The function can take any string value as an input and it will return the specified substring value. The number of times the substring is present in it.

Example:

  • First of all, We need to take a string value. In the below python code, You can see, I have taken the value as “John is good but john talk less”.
  • Then we need to store the specified substring value in some variable “store”.
  • Now print the “store” and it will return the substring occurrence. Which is the number of times it is present?

Code for python string count()

Below represents the python code for string count()

msg = "John is good but John talk less"
store = msg.count("John")
print(store)

After writing the above Python code (string count), Ones you will print “store” then the output will appear “2” as “John” is present two times. Also, you can refer to the below screenshot.

Python string function count
Python string count()

This way, we can use the Python string count() method to count the number of occurrences of a substring in string python.

Read: Append to a string Python + Examples

Check if a substring in a string in Python

Let us check if a substring in a string in Python. We can use if condition, and ” in “ operator is used to check substring in a string in Python.

Example:

string = ' Welcome to Python '
if "Welcome" in string:
print('yes')
else:
print('No')

After writing the above Python code (python the substring in a string), Ones you will print then the output will appear ” Yes “ as ” Welcome ” is present in the string. Here, the in operator will return true if the substring is present in the string and false otherwise.

Also, you can refer to the below screenshot.

Python the substring in a string
Python substring in a string

This is how to check if a substring in a string in Python.

Read: Python compare strings

Python split string with multiple delimiters

In python, to break the string with multiple delimiters we use re.split() method a delimiter separates the string with comma-separated values.

Example:

import re
msg = " I want\n to learn, python as\nit is* easy."
print(re.split('; | , |\n|\*', msg))

After writing the above Python code (Python split multiple delimiters), Ones you will print then the output will appear ” [‘ I want’, ‘ to learn, python as’, ‘it is’, ‘easy.’] ” Here, it will split with a delimiter comma and space. Also, you can refer to the below screenshot.

Python split string multiple delimiters
Python split string with multiple delimiters

This is how to split string with multiple delimiters in Python.

Read: Python program to reverse a string with examples

Python split string to substring using split() method

Let us see how to split a string to substring using split() method in Python.

  • Using the Python split() method we can break a string into pieces. These pieces return as a list.
  • To split any string we have a built-in split() which will split the string into a list.
  • The function can take any string as an input and it can produce a list as an output.

Example:

  • First of all, We need to take a string value. In the below python code, You can see, I have taken the value as “Welcome to Python Guide”.
  • Then we need to store the string value in some variable “value”.
  • Now print the “value” and it will give the list.

Code for python string split()

Below represents the python code to split the string.

value = 'Welcome to Python Guide'
print(value.split())
  • After writing the above Python code ( string split), Ones you will print value.split() then the output will appear as a list ‘[‘Welcome’, ‘to’, ‘Python’, ‘Guide’]’. Also, you can refer to the below screenshot.
Python string split function
Python split string to substring

This is how to use the Python split() method to split string.

Read: Python string formatting with examples.

Python string startswith substring

Let us see how to use the Python string startswith() method.

  • The Python startswith() method returns a boolean value. The startswith() returns true if the specified string starts with the prefix if not, it will return false. We can use this method if we want to get the first string value.
  • To get the first value from the string the built-in startswith() methods is used.
  • The function can take any string value as an input and it will return the true value if the specified substring match.

Example:

  • First of all, We need to take a string value. In the below python code, You can see, I have taken the value as “Hi John”.
  • Then we need to store the specified substring value in some variable “store”.
  • Now print the “store” and it will return the string value as “True”.

Python string startswith() code:

Below represents the python code for string startswith()

msg = "Hi John"
store = msg.startswith('Hi')
print(store)
  • After writing the above Python code (string startswith), Ones you will print “store” then the output will appear as a “True” as an output if specified condition is true if not, then false. Also, you can refer to the below screenshot.
Python string function startswith
Python string startswith()
  • If the substring does not starts with specified value then it will return “false” as an output. You can refer to the below screenshot.
Python string function startswith
Python string startswith()

Here is an example of Python string startswith substring.

Read Python dictionary extend

Python extract number from string

The number can be extracted from the string by using split function in python to convert string to list. Then the list comprehension helps us to iterate through the list and isdigit function helps to get the digit out of string.

Example:

my_string = "Welcome 2 python 5"
number = [int(w) for w in my_string.split() if w.isdigit()]
print(number)

After writing the above code (python extract number from string), Ones you will print “number” then the output will appear as “ [2 5] ”. Here, we will use isdigit() method to get the digit from the string.

You can refer to the below screenshot python extract number from string.

Python extract number from string
Python extract number from string

The above Python code we can use to extract number from string in Python.

Check if a string contains a word in python

The easiest way to check if a string contains a word is ” in “ operator in Python. This operator returns true if the string contains a word otherwise, it returns false.

Example:

my_str = "Rahul is good player"
check = "good" in my_str
print(check)

After writing the above code (check if a string contains word in python), Ones you will print “check” then the output will appear as “ True ”. Here, we will use in operator to check if a string contain that word or not.

You can refer to the below screenshot check if a string contains word in python

Check if a string contains word in python
Check if a string contains word in python

The above Python code, we can use to check if a string contains a word in python.

Longest palindromic substring python

To get longest palindrome substring, we will check each substring whether the substring is a palindrome or not.

We will loop through the string treating each character as the middle of the palindrome and try to build the palindrome by comparing characters on the left with characters on the right.

Example:

class find(object):
   def longestPalindrome(self, x):
      v = [[False for i in range(len(x))] for i in range(len(x))]
      for i in range(len(x)):
         v[i][i] = True
      max_length = 1
      start = 0
      for l in range(2,len(x)+1):
         for i in range(len(x)-l+1):
            end = i+l
            if l==2:
               if x[i] == x[end-1]:
                  v[i][end-1]=True
                  max_length = l
                  start = i
            else:
               if x[i] == x[end-1] and v[i+1][end-2]:
                  v[i][end-1]=True
                  max_length = l
                  start = i
      return x[start:start+max_length]
obj1 = find()
print(obj1.longestPalindrome("ZABBABBACD"))

After writing the above code (longest palindromic substring python), Ones you will print “obj1.longestPalindrome(“ZABBABBACD”)” then the output will appear as “ ABBABBA ”. Here, we get the longest palindromic substring.

You can refer to the below screenshot longest palindromic substring python

Longest palindromic substring python
Longest palindromic substring python

This is how to find longest palindromic substring python.

How to find last index of a string in Python

Let us see how to find last index of a string in python.

The rindex() method is used for finding the last index of a string in python.

Example:

my_str = "Hello, how are you"
f = my_str.rindex("u")
print(f)

After writing the above code (last index of a string python), you will print “f” then the output will appear as “ 17 ”. Here, the rindex() method returns the last index of a specified value or raises an exception if no such index exists.

You can refer to the below screenshot last index of a string python.

How to find last index of a string in Python
How to find last index of a string in Python

The above Python code, we can use to find last index of a string in Python.

Check if a python string contains another string

In other object-oriented languages, we can use contains method to check if a python string contains another string.

In python, there are some ways to check if a python string contains another string.

1- Using in operator

We can use in operator to check if a python string contains another string or not.

Using in operator is a clear and nit approach to check if the string contains another string.

Let’s see an example for this

Example:

mystring = "I love Python"

print("Python" in mystring)
print("Java" in mystring)

See the output here

How to check if a python string contains another string
check if a python string contains another string

In the above example, we saw that since “Python” exists in the string so it returned True and since “Java” is not present inside the string so it returned False.

2- Using find() method

One more way to check if a python string contains another string or not is to use find(). Which is a python-inbuilt method.

The find() method returns the first occurrence of the specified value.

It returns -1 if the value is not found.

Syntax

string.find(value, start, end)

Where start and end arguments are optional.

Let’s see an example for this

Example

mystring = "I love Python"
x = mystring.find("Python")
print(x)

Now see the output here

How to use find method in python
How to check if a python string contains another string

Example

x = mystring.find("Python")
y = mystring.find("java")
print(x)
print(y)

The out put will be 7 and – 1. – 1, since java is not present in side the string.

find a string inside a string in python
check if a python string contains another string

Example:

mystring = "I love Python very much"
x = mystring.find("o",2,8)

print(x)

See the output here

How to check if a python string contains another string
check if a python string contains another string

3- Using index() method

We can use the index() method to find the starting index of the first occurrence of a string inside the string.

If the string specified is not present inside the string then it will throw an exception.

Let’s see an example for the same

Syntax

string.index(value, start, end)

Where start and end are optional.

Example:

mystring = "I love Python very much"
x = mystring.index("Python")

print(x)

See the out put here

index method in python
index() method in python

Example:

mystring = "I love Python very much"
x = mystring.index("o",2,8)

print(x)
index method with arguments in python
index() method in Python

This is how to check if a python string contains another string.

You may like the following Python examples:

In this Python tutorial, we learned, Python find substring in string and the below examples:

  • How to find substring in a string
  • Find substring from string using Python string find() method
  • Check if a string contains a substring in Python
  • Count substring in string python using count() method
  • Check if a substring in a string in Python
  • Python split string with multiple delimiters
  • Python split string to substring using split() method
  • Python string startswith substring
  • Extract number from string in Python
  • Check if a string contains a word in python
  • How to find longest palindromic substring in Python
  • How to find last index of a string in Python
  • How to check if a python string contains another string