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

2024-04-25 02:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中有没有直接的方法来剥离一个字符串并得到开始索引和结束索引?在

示例:给定字符串' hello world! ',我想要剥离字符串'hello world!',以及起始索引2和and索引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()

但我想知道Python或某个流行的库是否提供了任何内置的方法来实现这一点。在


Tags: andthe方法字符串helloworldstringindex
3条回答

事实上,你有必要的方法来完成这项任务。stripfind和{}就是你所需要的。在

s = '  hello world!   '
s1 = s.strip()
first_index = s.find(s1)
end_index = first_index + len(s1) - 1

最有效的方法是分别调用lstrip和{}。例如:

s = '  hello world!   '
s2 = s.lstrip()
s3 = s2.rstrip()
ix = len(s) - len(s2)
ix2 = len(s3) + ix

这样可以得到:

^{pr2}$

一种选择(可能不是最直接的)是使用正则表达式来实现:

>>> 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)

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

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

相关问题 更多 >