Thursday, 22 March 2018

Find string between two sub-strings Python |

This can be done by following way based on requirements :

  • index
  • rindex

(it's equivalent of regex (.*) and (.*?) groups)

s = "123123STRINGabcabc"

using index :

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""
using rindex: 

def find_between_r( s, first, last ):
    try:
        start = s.rindex( first ) + len( first )
        end = s.rindex( last, start )
        return s[start:end]
    except ValueError:
        return ""

print find_between( s, "123", "abc" )
>> 123STRING


print find_between_r( s, "123", "abc" )
>> STRINGabc


No comments:

Post a Comment