Python - Get substring between brackets


Python - Get substring between brackets

To get the substring between brackets in a string in Python, first find the index of opening bracket, then find the index of closing bracket that occurs after the opening bracket, 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 brackets in a string in Python, using string find() method and string slicing, with examples.

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

Consider that we are given a string in x. We need to find the substring that is present between brackets in the string x.

Steps

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

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

Python Program

# Input string
x = "Hello Wo[Apple123]rld!"

# Bracket characters
opening_bracket = "["
closing_bracket = "]"

# Find indices of brackets
index_1 = x.find(opening_bracket)
if index_1 != -1:
    index_2 = x.find(closing_bracket, index_1)

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

# Print the result
print(substring)

Output

Apple123

Related Tutorials

Summary

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