Re: get each pair from a string.

Discussion in 'Python' started by Vlastimil Brom, Oct 21, 2012.

  1. 2012/10/21 Vincent Davis <>:
    > 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
    Vlastimil Brom, Oct 21, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Emile van Sebille

    Re: get each pair from a string.

    Emile van Sebille, Oct 22, 2012, in forum: Python
    Replies:
    9
    Views:
    210
    Mark Lawrence
    Oct 24, 2012
  2. Ian Kelly

    Re: get each pair from a string.

    Ian Kelly, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    131
    Ian Kelly
    Oct 21, 2012
  3. Mark Lawrence

    Re: get each pair from a string.

    Mark Lawrence, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    151
    Mark Lawrence
    Oct 21, 2012
  4. Emile van Sebille

    Re: get each pair from a string.

    Emile van Sebille, Oct 22, 2012, in forum: Python
    Replies:
    0
    Views:
    181
    Emile van Sebille
    Oct 22, 2012
  5. Ian Kelly

    Re: get each pair from a string.

    Ian Kelly, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    162
    Ian Kelly
    Oct 21, 2012
Loading...

Share This Page