Python extract substring between two characters | Example code

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

Simple example code get 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 and suggestions on this Python substring char tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.