get each pair from a string.

rusi rustompmody at gmail.com
Tue Oct 23 00:59:49 EDT 2012


On Oct 22, 9:19 pm, rusi <rustompm... at gmail.com> wrote:
> On 10/21/2012 11:33 AM, Vincent Davis wrote:
>
> > I am looking for a good way to get every pair from a string. For example,
> > input:
> > x = 'apple'
> > output
> > 'ap'
> > 'pp'
> > 'pl'
> > 'le'
>
> Maybe zip before izip for a noob?
>
> >>> s="apple"
> >>> [a+b for a,b in zip(s, s[1:])]
>
> ['ap', 'pp', 'pl', 'le']

Daniel wrote:
> This is a little bit faster:
>
> s = "apple"
> [s[i:i+2] for i in range(len(s)-1)]

Nice! I always find pairs of structural decomposition of input vs
recomposition of output interesting.
In this case the use of slices:
to decompose: s -> s[1:]
vs doing s[i:i+2]



More information about the Python-list mailing list