2

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.

1
  • 1
    Use re.findall() to find all the matches of <.*?>. This will return a list, you can then get the one with the specific index. Commented Jul 2, 2021 at 19:03

2 Answers 2

5

you can get a substring between two indexes like this

aString[start: end]

where start and end are integers

Sign up to request clarification or add additional context in comments.

1 Comment

thank for the answer. I have similar problem, Is it possible to make a loop to get all strings between < and >? The output result should be like this: carrot orange pineapple grape watermelon mangosteen
0

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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.