Sometimes, while working with Python strings, we can have a problem in which we need to extract the substrings between certain characters and can be brackets. This can have application in cases we have tuples embedded in string. Lets discuss certain ways in which this task can be performed.
Method #1 : Using regex
One way to solve this problem is by using regex. In this we employ suitable regex and perform the task of extraction of required elements.
The original string is : geeks(for)geeks is (best) The element between brackets : ['(for)', '(best)']
Method #2 : Using list comprehension +
isintance() + eval()
The combination of above methods can also be used to solve this problem. In this eval() assume the brackets to be tuples and helps the extraction of strings within them.
The original string is : [(234, ), 4, (432, )] The element between brackets : ['(234, )', '(432, )']
- Python | Extract Numbers in Brackets in String
- Python - Extract K length substrings
- Python | Remove square brackets from list
- Python - Matching Pairs of Brackets
- Python program to extract Strings between HTML Tags
- Python | Extract key-value of dictionary in variables
- numpy.extract() in Python
- Python Regex to extract maximum numeric value from a string
- Python Slicing | Extract ‘k’ bits from a given position
- Python program to extract Email-id from URL text file
- Python | Program to extract frames using OpenCV
- Python | Extract similar index elements
- Python | Extract K sized strings
- Extract images from video in Python
- Python | Extract words from given string
- Python | Extract URL from HTML using lxml
- Python | Pandas Series.str.extract()
- Python | Extract numbers from string
- Python | Extract only characters from given string
- Python | Extract numbers from list of strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.