我想创建一个元组列表,我想:
# String
input= "M i n d"
# List of tuple
output = [(0, 3), (4, 9), (10, 18), (19, 19)]
我能够编写这个逻辑(在最后一个元组中有一个错误),但我觉得必须有一种更聪明的方法来编写它。有什么想法吗
string = "M i n d"
coltuple = []
for a in string:
if a.isalpha() == True:
start = string.index(a)
next_string = string[(start + 1) :]
if next_string:
for b in next_string:
if b.isalpha() == True:
end = string.index(b) - 1
print("End:", end)
break
else:
end = len(string) - 1
coltuple += [(start, end)]
print(coltuple)
这可以通过使用
re
模块来解决印刷品:
[(0, 3), (4, 9), (10, 18), (19, 19)]
如果要使用这些值索引到字符串中,最好使用
token.end()
而不是token.end()-1
注意:从常规表达式中删除了捕获括号。它是
r'(\S+\s*)
这就是我想到的:
相关问题 更多 >
编程相关推荐