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()
但我不知道Python或一个通俗图书馆是否提供任何内置的方式来做到这一点。
我不认为有内置的方式。你的代码非常简洁,实际上只是'str_stripped = str.strip()','index_start = str.find(str_stripped)'和'index_end = index_start + len(str_stripped)'这三行。其余的都是多余的。 –
@LukeTaylor:它很简洁,但正如评论说他正在对字符串进行多次传球。当然,你可以编写一个'strip()'函数,它可以在执行一遍时返回所需的输出。 –