How can i parse a long string that come from a .txt file every
2 characters
?
How can i parse a long string that come from a .txt file every
2 characters
?
Try
print re.findall(r'[\S]{1,2}', "The quick brown fox jumped over the lazy dog")
>>
['Th', 'e', 'qu', 'ic', 'k', 'br', 'ow', 'n', 'fo', 'x', 'ju', 'mp', 'ed', 'ov', 'er', 'th', 'e', 'la', 'zy', 'do', 'g']
OR
print re.findall(r'.{1,2}', "The quick brown fox jumped over the lazy dog")
>>
['Th', 'e ', 'qu', 'ic', 'k ', 'br', 'ow', 'n ', 'fo', 'x ', 'ju', 'mp', 'ed', ' o', 've', 'r ', 'th', 'e ', 'la', 'zy', ' d', 'og']
Update
For you specific requirement:
>>> print re.findall(r'[\S]{1,2}', "08AB78UF")
['08', 'AB', '78', 'UF']
>>>
You can just zip two strings, with a gap of one offset
>>> data = "foobar"
>>> map(''.join, zip(data, data[1:]))
['fo', 'oo', 'ob', 'ba', 'ar']
And a similar solution using itertools.izip
>>> from itertools import izip
>>> map(''.join, izip(data, data[1:]))
['fo', 'oo', 'ob', 'ba', 'ar']
If you are using Py3.X, convert the map to LC
>>> [''.join(e) for e in izip(data, data[1:])]
['fo', 'oo', 'ob', 'ba', 'ar']
As @Duncan mentioned, the sub-strings would overlap. In case if you want non-overlapping substrings, either refer @Duncan's answer, or @Duncan's comment or the grouper recipe
>>> [''.join(e) for e in list(izip_longest(*[iter(data)] * 2,fillvalue=''))]
['fo', 'ob', 'ar']
You can easily join the resultant list to a string
>>> ' '.join(''.join(e) for e in izip(data, data[1:]))
'fo oo ob ba ar'