简体   繁体   中英

Python: Get string between two character with specific index

I am very beginner in Python.

aString = 'fruit list is: <carrot>, <orange>, <pineapple>, <grape>, <watermelon>, <mangosteen>'

From my aString, sometime I need a string 'carrot' ; sometime I need a string 'watermelon' ; sometime I need a string 'mangosteen' .

Does Python have a function to get string between two character with specific index?

I am very thankful if somebody can help to solve this problem.

you can get a substring between two indexes like this

aString[start: end]

where start and end are integers

It's too late but that's my own function:

def Between(first, second, position, string, direction='forward'):
    # if you have the index of the second character you can use it but add direction = 'back' or anything except '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

# for example:
string = "abc(defg)hijklmenop"
print(Between("(", ")", 3, string)) # direction = 'forward'
print(Between("(", ")", 8, string, direction='back'))

# Also it works in this case:
string = "abcd(efg(hij)klmno)pqrstuvwxyz"
print(Between("(", ")", 4, string)) # direction = 'forward'
print(Between("(", ")", 18, string, direction='back'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM