Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to get the string between brackets in a string in python

# I made this function myself

def Between(first, second, position, string, direction='forward'):
    result = ""
    pairs = 1

    if direction == 'forward':
        for i in string[position+1:]:
            if i == first: pairs += 1

            elif i == second: pairs -= 1

            if pairs==0: break

            result = result+i

    else:
        for i in (string[:position])[::-1]:
            if i == second: pairs += 1

            elif i == first: pairs -= 1

            if pairs==0: break

            result = i+result

    return result

# You need to know the position of the bracket that you want in the string

string = "2(48) = 12(-x)"
print(Between("(", ")", 10, string)) # if direction = 'forward' position should be the index of '('
print(Between("(", ")", 4, string, direction="back")) # if direction ≠ 'forward' position should be the index of ')'

# But If you know that the string contains only two main brackets you can do this:

# direction = "forward"
string = "abc(efg(hij)kl)mno"
position = string.index("(")
print(Between("(", ")", position, string))

# direction = "back"
string = "abc(efg(hij)kl)mno"
position = len(string) - string[::-1].index(")") - 1
print(Between("(", ")", position, string, direction='back'))

# And you can also edit the function as you want
Comment

PREVIOUS NEXT
Code Example
Python :: isclass function in python xml 
Python :: palindrome program in python 
Python :: create a number of variables based on input in python 
Python :: when to use static method in python 
Python :: python yield async await 
Python :: flask-sqlalchemy inheritance 
Python :: geopandas plot raster and vector 
Python :: running setup.py install for rjsmin ... error 
Python :: pandas assign multiple columns 
Python :: Find From Table Django 
Python :: pytrend 
Python :: Creating column based on existing column 
Python :: enumerate for string 
Python :: How to print specific figure in python 
Python :: checking time in time range 
Python :: python list chunks using yield 
Python :: jupyter notebook print formatted text 
Python :: prefix in python 
Python :: the best ide for python 
Python :: machine learning project outline 
Python :: pandas df to R df 
Python :: when was barracoon written 
Python :: odoo wizard current user login 
Python :: how to place an id to every element in list in python 
Python :: plt.savefig no frame 
Python :: create a list with user defined name of list 
Python :: check it two words are anagram pyhton 
Python :: Ignoring NaNs with str.contains 
Python :: do function for each 10sec with pyside2 
Python :: queue data structure in python 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =