给定一个字符串,如"8584320342564023450211233923239923239110001012346596"
,如何获得所有连续的 4 位子序列?
例如,上面的字符串将产生:8548
, 5843
, 8432
, 0342
, ...
给定一个字符串,如"8584320342564023450211233923239923239110001012346596"
,如何获得所有连续的 4 位子序列?
例如,上面的字符串将产生:8548
, 5843
, 8432
, 0342
, ...
我认为这可以满足您的要求:
es = '8584320342564023450211233923239923239110001012346596'
strings = [es[x:x+4] for x in xrange(0, len(es)-3)]
输出
>> strings
Out[42]:
['8584',
'5843',
'8432',
'4320',
'3203',
'2034',
'0342',
'3425',
'4256',
'2564',
'5640',
'6402',
'4023',
'0234',
'2345',
'3450',
'4502',
'5021',
'0211',
'2112',
'1123',
'1233',
...
您可以使用以下代码获取n
从i
th位置开始的字符子序列:
str[i:i+n]
请注意,第 0个位置是字符串的开头,而不是第 1个。我的意思是str[0:0+n]
会给你前 n 个字符而不是str[1:1+n]
这是代码:
s = "8584320342564023450211233923239923239110001012346596"
for i in range(len(s) - 3):
print(s[i:i+4])
data = "8584320342564023450211233923239923239110001012346596"
span = 4
for i in range(len(data) - span + 1):
print data[i:i+span]
这是一个正则表达式解决方案:
import re
re.findall("[0-9]{4}","8584320342564023450211233923239923239110001012346596")
编辑:感谢评论,我看到你真正想要的是所有重叠的匹配。我在这里找到了一个现有的 stackoverflow 答案: Python regex find all重叠匹配?
使用它作为所需正则表达式的提示。在您的情况下,您可以使用:
>>> re.findall("(?=(\d{4}))","8584320342564023450211233923239923239110001012346596")
['8584', '5843', '8432', '4320', '3203', '2034', '0342', '3425', '4256', '2564', '5640', '6402', '4023', '0234', '2345', '3450', '4502', '5021', '0211', '2112', '1123', '1233', '2339', '3392', '3923', '9232', '2323', '3239', '2399', '3992', '9923', '9232', '2323', '3239', '2391', '3911', '9110', '1100', '1000', '0001', '0010', '0101', '1012', '0123', '1234', '2346', '3465', '4659', '6596']
>>> from itertools import islice
>>> line = "8584320342564023450211233923239923239110001012346596"
>>> map(''.join, zip(*(islice(line,i,None) for i in range(4))))
['8584', '5843', '8432', '4320', '3203', '2034', '0342', '3425', '4256', '2564', '5640', '6402', '4023', '0234', '2345', '3450', '4502', '5021', '0211', '2112', '1123', '1233', '2339', '3392', '3923', '9232', '2323', '3239', '2399', '3992', '9923', '9232', '2323', '3239', '2391', '3911', '9110', '1100', '1000', '0001', '0010', '0101', '1012', '0123', '1234', '2346', '3465', '4659', '6596']
这会将输出设置为包含一个列表列表,其中每个 4 个字符序列都有一个叶子:
output = []
for i in range(len(input) - 3):
output.append(input[i:i+4])