Reputation: 35
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.
Upvotes: 2
Views: 7765
Reputation: 19
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'))
Upvotes: -1
Reputation: 68
you can get a substring between two indexes like this
aString[start: end]
where start and end are integers
Upvotes: 5