Rem*_*man 2 python string split position python-3.x
例:
s=" 300 january 10 20 "
mylist = s.split()
mylist = ['300', 'january', '10', '20']
Run Code Online (Sandbox Code Playgroud)
如何创建一个列表,在拆分前添加元素的字符串位置:
mylistStringPos = [['300',startpos:endpos],...]
mylistStringPos = [['300',2:5], '['january',12:19]', '['10',25:27]', '['20',34:36]']]
Run Code Online (Sandbox Code Playgroud)
Python中有没有办法做到这一点?
您可以使用re该\S+模式来匹配非空白的文本和访问块m.group(),m.start()并m.end()收集必要的数据:
import re
s=" 300 january 10 20 "
print([[x.group(), x.start(), x.end()] for x in re.finditer(r'\S+', s)])
# => [['300', 2, 5], ['january', 12, 19], ['10', 25, 27], ['20', 34, 36]]
Run Code Online (Sandbox Code Playgroud)
请参阅此Python演示