Getting two characters from a string in python

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

I have:

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

and i like it

a
b
c
d

but i need to get

ab
cd

I am new to python .. is there any way?

+5
source share
3 answers
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 generic 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)
+7
source

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

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

Here I use the range operator of three arguments to indicate the start, end and step (see http://docs.python.org/library/functions.html ).

, . , range len(long_str).

+11

I'm also new to Python, take a look at my code:

long_str = "abcdefghi"

state1=True
state2=False
state3=True

for item in long_str:
    if state1:
       print(item,end="")
       state3=True

    if state2:
       print(item)
       state1=True
       state2=False
       state3=False

    if state3:
       state1=False
       state2=True

Output:

ab
cd
ef
gh
i
-1
source

All Articles