【问题标题】:Python: Function to return index starting from the end for a stringPython:从字符串末尾开始返回索引的函数
【发布时间】:2017-02-08 17:14:03
【问题描述】:

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

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

string.foo('mainly ') 返回 31,而不必使用 string.index('mainly ')+len('mainly ')?

【问题讨论】:

  • 可能是一个正则表达式,在“主要”之后寻找空格
  • 可以使用正则表达式或拆分等来完成它,但使用+len()更容易。你为什么不想使用它?
  • 我只是想知道是否有更清洁的方法可以做到这一点,但似乎+len() 是最好的方法。

标签: python string indexing slice


【解决方案1】:

两行即可轻松实现:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2013-10-27
    • 2021-01-10
    相关资源
    最近更新 更多