Python - Get substring between two specific characters


Python - Get substring between two specific characters

To get the substring between two specific characters in a string in Python, first find the index of first specific character, then find the index of second specific character that occurs after the first specific character, and finally with the two indices in hand, slice the string and find the required substring.

In this tutorial, you will learn how to get the substring between two specific characters in a string in Python, using string find() method and string slicing, with examples.

1. Get substring between two characters using string find() method and string slicing in Python

Consider that we are given a string in x, and the specific characters in ch1 and ch2. We need to find the substring that is present between these two character in the string x.

Steps

  1. Find the index of ch1 in string x using string find() method. Let us store the returned index in index_1.
index_1 = x.find(ch1)
  1. If index_1 is not -1, i.e., there is an occurrence of ch1 in the string x, then find the occurrence of ch2 after index_1 in the string x. Assign the returned value to index_2.
index_2 = x.find(ch2, index_1)
  1. If both index_1, and index_2 are not -1, then find the substring between the specified characters using the following string slice expression.
substring = x[index_1 + 1 :index_2]

The complete program to find the substring between two specific characters in a string is given below.

Python Program

# Input string
x = "Hello, World!"

# Specific characters
ch1 = "e"
ch2 = "r"

# Find indices of specific characters
index_1 = x.find(ch1)
if index_1 != -1:
    index_2 = x.find(ch2, index_1)

if index_1 != -1 and index_2 != -1:
    # Get the substring between specific characters
    substring = x[index_1 + 1 :index_2]
else:
    print("Error: One or both of the characters not present")

# Print the result
print(substring)

Output

llo, Wo

Related Tutorials

Summary

In this tutorial, we learned how to get the substring between two specific characters in a string in Python using string find() method and string slicing, with the help of examples.