Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over a string 2 (or n) characters at a time in Python

Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like "+c-R+D-E" (there are a few extra letters).

I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.

# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
  print op, code

Are there some better/cleaner ways to do this?

like image 947
Richard Levasseur Avatar asked Jul 22 '09 01:07

Richard Levasseur


People also ask

How do you iterate multiple characters in a string in Python?

To iterate over a string in Python, we use loops like (for loop or while loop). We also can use RANGE with for loop to iterate through a range of characters in a string. Another way we use INDEX is to return each character of a particular index.

How do you iterate 2 in Python?

Use the izip() Function to Iterate Over Two Lists in Python The izip() function also expects a container such as a list or string as input. It iterates over the lists until the smallest of them gets exhausted. It then zips or maps the elements of both lists together and returns an iterator object.

Can we iterate string in Python?

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.


2 Answers

I don't know about cleaner, but there's another alternative:

for (op, code) in zip(s[0::2], s[1::2]):     print op, code 

A no-copy version:

from itertools import izip, islice for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):     print op, code 
like image 176
Pavel Minaev Avatar answered Sep 20 '22 09:09

Pavel Minaev


Maybe this would be cleaner?

s = "+c-R+D-e"
for i in xrange(0, len(s), 2):
    op, code = s[i:i+2]
    print op, code

You could perhaps write a generator to do what you want, maybe that would be more pythonic :)

like image 42
Paggas Avatar answered Sep 22 '22 09:09

Paggas