-1

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.

L8R
  • 401
  • 5
  • 21
  • 1
    Do you what is in between the first occurence of the first character and the first occurence of the second character after that? Or something else? Please clarify. – pigrammer Oct 16 '22 at 21:21
  • What have you tried yourself? Do you know how to get the `.index()` of a character in a string? Did you look at how to slice a string from `a:b`? Why are you looking to avoid regex, when it's actually the right tool? – Grismar Oct 16 '22 at 21:21
  • @Grismar I haven't tried anything because I don't know the right approach. Yes I know how to get the index of a character. No, I didn't know you could slice a string, I am avoiding regex because I am unfamiliar with it, but am open to it. – L8R Oct 16 '22 at 21:26
  • 1
    Does this answer your question? [Find string between two substrings](https://stackoverflow.com/questions/3368969/find-string-between-two-substrings) the answer by @ansetou is what you are searching for – Rabinzel Oct 16 '22 at 21:35

2 Answers2

1

What about a simple find?

string = "aabcdefgg"
start = string.find("a") + 1
end = string.find("g", start) + 1
print(string[start:end])  # abcdefg
bitflip
  • 3,436
  • 1
  • 3
  • 22
1

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
L8R
  • 401
  • 5
  • 21
Nazmus Sakib
  • 68
  • 1
  • 6