Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR 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
 
PREVIOUS NEXT
Tagged: #string #brackets #string #python
ADD COMMENT
Topic
Name
1+4 =