Python Reverse Find in String

前端 未结 2 2029
渐次进展
渐次进展 2020-12-14 14:43

I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index.

An example: I want to find the index of the

2条回答
  •  感情败类
    2020-12-14 15:17

    I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop:

    orig = s = "Hello, I am 12! I like plankton but I don't like Baseball."
    found = tail = ''
    nthlast = 2
    lookfor = 'I'
    for i in range(nthlast):
        tail = found+tail
        s,found,end = s.rpartition(lookfor)
        if not found:
            print "Only %i (less than %i) %r in \n%r" % (i, nthlast, lookfor, orig)
            break
        tail = end + tail
    else:
        print(s,found,tail)
    

提交回复
热议问题