Python:函数return从字符串末尾开始索引

Python: Function to return index starting from the end for a string

是否有函数 return 结束索引而不是子字符串的开始索引。例如,对于

string = 'the rain in spain stays mainly in the plain'

string.foo('mainly ') returns 31,而不是必须使用 string.index('mainly ')+len('mainly ')

两行即可轻松实现:

def get_sub_end(s, sub):
    f = s.find(sub)
    return f if f == -1 else f + len(sub)

用法:

test_str = 'the rain in spain stays mainly in the plain'

if __name__ == '__main__':
    print get_sub_end(test_str, "mainly ")  # >>> 31
    print get_sub_end(test_str, "undefined ")  # >>> -1