在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或某个流行的库是否提供了任何内置的方法来实现这一点。在
事实上,你有必要的方法来完成这项任务。}就是你所需要的。在
strip
、find
和{最有效的方法是分别调用}。例如:
lstrip
和{这样可以得到:
^{pr2}$一种选择(可能不是最直接的)是使用正则表达式来实现:
在
^\s*(\S.*?)\s*$
模式中:^
是字符串的开头\s*
零个或多个空格字符(\S.*?)
是一个捕获组,它将以non-greedy方式捕获非空格字符后跟任意次数的任何字符$
是字符串的结尾相关问题 更多 >
编程相关推荐