剥离字符串并获取开始索引和结束索引
Stripping a string and getting start index and end index
在Python中有没有直接的方法来剥离字符串并获取开始索引和结束索引?
示例:给定字符串 ' hello world! '
,我想要剥离的字符串 'hello world!'
以及起始索引 2
和索引 14
.
' hello world! '.strip()
仅 returns 剥离的字符串。
我可以写一个函数:
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 或一个流行的库是否提供任何内置方法来这样做。
一个选项(可能不是最直接的)是使用正则表达式来完成:
>>> 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*
零个或多个 space 个字符
(\S.*?)
是一个捕获组,它将以 non-greedy 方式捕获非 space 字符后跟任何字符任意次数
$
是字符串的结尾
最有效的方法是分别调用 lstrip
和 rstrip
。例如:
s = ' hello world! '
s2 = s.lstrip()
s3 = s2.rstrip()
ix = len(s) - len(s2)
ix2 = len(s3) + ix
这给出:
>>> s3
'hello world!'
>>> ix
2
>>> ix2
14
>>>
事实上你有必要的方法来完成这个任务。 strip
、find
和 len
就是您所需要的。
s = ' hello world! '
s1 = s.strip()
first_index = s.find(s1)
end_index = first_index + len(s1) - 1
在Python中有没有直接的方法来剥离字符串并获取开始索引和结束索引?
示例:给定字符串 ' hello world! '
,我想要剥离的字符串 'hello world!'
以及起始索引 2
和索引 14
.
' hello world! '.strip()
仅 returns 剥离的字符串。
我可以写一个函数:
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 或一个流行的库是否提供任何内置方法来这样做。
一个选项(可能不是最直接的)是使用正则表达式来完成:
>>> 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*
零个或多个 space 个字符(\S.*?)
是一个捕获组,它将以 non-greedy 方式捕获非 space 字符后跟任何字符任意次数$
是字符串的结尾
最有效的方法是分别调用 lstrip
和 rstrip
。例如:
s = ' hello world! '
s2 = s.lstrip()
s3 = s2.rstrip()
ix = len(s) - len(s2)
ix2 = len(s3) + ix
这给出:
>>> s3
'hello world!'
>>> ix
2
>>> ix2
14
>>>
事实上你有必要的方法来完成这个任务。 strip
、find
和 len
就是您所需要的。
s = ' hello world! '
s1 = s.strip()
first_index = s.find(s1)
end_index = first_index + len(s1) - 1