get each pair from a string.

Vlastimil Brom vlastimil.brom at gmail.com
Sun Oct 21 17:48:43 EDT 2012


2012/10/21 Vincent Davis <vincent at vincentdavis.net>:
> I am looking for a good way to get every pair from a string. For example,
> input:
> x = 'apple'
> output
> 'ap'
> 'pp'
> 'pl'
> 'le'
>
> I am not seeing a obvious way to do this without multiple for loops, but
> maybe there is not :-)
> In the end I am going to what to get triples, quads....... also.
>
> Thanks
> Vincent
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Hi,
just another - probably less canonical - approach using the new regex
library could be (assuming the input sequence is always a string):

>>> import regex # http://pypi.python.org/pypi/regex
>>> regex.findall("..", "abcdefghijklm", overlapped=True)
['ab', 'bc', 'cd', 'de', 'ef', 'fg', 'gh', 'hi', 'ij', 'jk', 'kl', 'lm']
>>> regex.findall("...", "abcdefghijklm", overlapped=True)
['abc', 'bcd', 'cde', 'def', 'efg', 'fgh', 'ghi', 'hij', 'ijk', 'jkl', 'klm']
>>>

If the newline \n could appear in the text, an appropriate pattern
would be e.g. "(?s)..."

regards,
   vbr



More information about the Python-list mailing list