繁体   English   中英

Python:从字符串末尾返回索引的函数

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

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

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

string.foo('mainly ') string.index('mainly ')+len('mainly ') string.foo('mainly ')返回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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM