Python example extract substring between two characters
A simple example code gets text between two char in Python.
Using Regular expression
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))
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)
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)
Python read-string between two substrings
import re s = 's1Texts2' result = re.search('s1(.*)s2', s) print(result.group(1))
Do comment if you have any doubts or suggestions on this Python substring char tutorial.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.