How to get everything between two characters?

Question:

Example:

string = "aabcdefgg"
string.inbetween("a", "g") # abcdefg

I want to avoid regex, if possible.

Edit:
I want to get the characters in between the first occurrence of both arguments.

Asked By: Vlone

||

Answers:

What about a simple find?

string = "aabcdefgg"
start = string.find("a") + 1
end = string.find("g", start) + 1
print(string[start:end])  # abcdefg
Answered By: bitflip

Getting the characters in between the first occurrence of both arguments:

def in_between(string,x,y)
    return string[string.index(x)+1:string.index(y)]
string = "aabcdefgg"
in_between(string,"a","g")  #abcdef

Your expected output in the side comment shows it’s the characters between the first occurrence of the first argument.

Getting the characters in between the last occurrence in the last argument:

def in_between(string,x,y)
    return string[string.index(x)+1:string.rindex(y)]
string = "aabcdefgg"
in_between(string,"a","g") # abcdefg
Answered By: Nazmus Sakib
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.