剥离字符串并获取起始索引和结束索引

Fra*_*urt 4 python strip

Python中是否有任何直接的方法来剥离字符串并获取起始索引和结束索引?

示例:给定字符串' hello world! ',我想要剥离的字符串'hello world!'以及起始索引2和和索引14.

' hello world! '.strip() 只返回剥离的字符串.

我可以写一个函数:

def strip(str):
    '''
    Take a string as input.
    Return the stripped string as well as the start index and end index.
    Example: '  hello world!   '  --> ('hello world!', 2, 14)
    The function isn't computationally efficient as it does more than one pass on the string.
    '''
    str_stripped = str.strip()
    index_start = str.find(str_stripped)
    index_end = index_start + len(str_stripped)
    return str_stripped, index_start, index_end

def main():
    str = '  hello world!   '
    str_stripped, index_start, index_end = strip(str)
    print('index_start: {0}\tindex_end: {1}'.format(index_start, index_end))

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

但我想知道Python或一个流行的库是否提供了任何内置的方法.

ale*_*cxe 6

一个选项(可能不是最直接的)是用正则表达式做的:

>>> import re
>>> s = '  hello world!   '
>>> match = re.search(r"^\s*(\S.*?)\s*$", s)
>>> match.group(1), match.start(1), match.end(1)
('hello world!', 2, 14)
Run Code Online (Sandbox Code Playgroud)

^\s*(\S.*?)\s*$模式中:

  • ^ 是一个字符串的开头
  • \s* 零个或多个空格字符
  • (\S.*?)是一个捕获组,它将以非贪婪的方式捕获非空格字符,后跟任意字符,任意次
  • $ 是一个字符串的结尾

  • 如果没有要删除的空格,这将无法正常工作.使用''\ s*''代替应该有所帮助 (2认同)