7

how to get in python from string not one character, but two?

I have:

long_str = 'abcd'
for c in long_str:
   print c

and it gives me like

a
b
c
d

but i need to get

ab
cd

I'm new in python.. is there any way?

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
Adomas
  • 289
  • 2
  • 4
  • 16
  • related "What is the most “pythonic” way to iterate over a list in chunks?" http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – jfs May 22 '10 at 20:06

2 Answers2

14

You can use slice notation. long_str[x:y] will give you characters in the range [x, y) (where x is included and y is not).

>>> for i in range(0, len(long_str) - 1, 2):
...   print long_str[i:i+2]
... 
ab
cd

Here I am using the three-argument range operator to denote start, end, and step (see http://docs.python.org/library/functions.html).

Note that for a string of odd length, this will not take the last character. If you want the last character by itself, change the second argument of range to len(long_str).

danben
  • 80,905
  • 18
  • 123
  • 145
7
for i, j in zip(long_str[::2], long_str[1::2]):
  print (i+j)

or

import operator
for s in map(operator.add, long_str[::2], long_str[1::2]):
   print (s)

itertools also provide a generalized implementation of this:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005