Skip to content

Python extract substring between two characters | Example code

  • by

You can do this with RegEx to extract substring between two characters in Python. You can use owe logic for it like index() function with for-loop or slice notation.

Python example extract substring between two characters

A simple example code gets text between two char in Python.

Using Regular expression

You have to import the re module for this example.

Apply re.search(pattern, string) with the pattern set to “x(.*?)y” to match substrings that begin with “x” and end with “y” and use Match.group() to get the desired substring.

import re

s = 'aHellodWorldaByed'
result = re.search('d(.*)a', s)
print(result.group(1))

Output:

Python extract substring between two characters

Using index() with for loop

s = 'Hello d World a Byed'

# getting index of substrings
id1 = s.index("d")
id2 = s.index("a")

res = ''
# getting elements in between
for i in range(id1 + len("d") + 1, id2):
    res = res + s[i]

print(res)

Output: World

Using index() with string slicing

s = ' Hello d World a Byed'

# getting index of substrings
id1 = s.index("")
id2 = s.index("d")

res = s[id1 + len("") + 1: id2]

print(res)

Output: Hello

Python read-string between two substrings

import re

s = 's1Texts2'
result = re.search('s1(.*)s2', s)
print(result.group(1))

Output: Text

Do comment if you have any doubts or suggestions on this Python substring char tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *