2

This sounds pretty basic but I ca't think of a neat straightforward method to do this in Python yet

I have a string like "abcdefgh" and I need to create a list of elements picking two characters at a time from the string to get ['ab','cd','ef','gh'].

What I am doing right now is this

output = []

for i in range(0,len(input),2):
  output.append(input[i:i+2])

Is there a nicer way?

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
atlantis
  • 3,056
  • 9
  • 30
  • 41

3 Answers3

4
In [2]: s = 'abcdefgh'

In [3]: [s[i:i+2] for i in range(0, len(s), 2)]
Out[3]: ['ab', 'cd', 'ef', 'gh']
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Just for the fun of it, if you hate for

>>> s='abcdefgh'
>>> map(''.join, zip(s[::2], s[1::2]))
['ab', 'cd', 'ef', 'gh']
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
1

Is there a nicer way?

Sure. List comprehension can do that.

def n_chars_at_a_time(s, n=2):
  return [s[i:i+n] for i in xrange(0, len(s), n)]

should do what you want. The s[i:i+n] returns the substring starting at i and ending n characters later.

n_chars_at_a_time("foo bar baz boo", 2)

produces

['fo', 'o ', 'ba', 'r ', 'ba', 'z ', 'bo', 'o']

in the python REPL.

For more info see Generator Expressions and List Comprehensions:

Two common operations on an iterator’s output are

  1. performing some operation for every element,
  2. selecting a subset of elements that meet some condition.

For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring.

List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations...

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245