views:

60

answers:

4

Let's say I have this little piece of code:

<?php 
$tmp = str_split('hello world!',2);
// $tmp will now be: array('he','ll','o ','wo','rl','d!');
foreach($tmp AS &$a) {
  // some processing
}
unset($tmp);
?>

How can I do this in Python v2.7?

I thought this would do it:

the_string = 'hello world!'
tmp = the_string.split('',2)
for a in tmp:
  # some processing
del tmp

but it returns an "empty separator" error.

Any thoughts on this?

+6  A: 
for i in range(0, len(the_string), 2):
    print(the_string[i:i+2])
SilentGhost
Or to return a list: [s[x:x + 2] for x in range(0, len(s), 2)]
twneale
thanks, this certainly did the trick :)
unreal4u
+1  A: 

tmp = the_string[::2] gives a copy of the_string with every second element. ...[::1] would return a copy with every element, ...[::3] would give every third element, etc.

Note that this is a slice and the full form is list[start:stop:step], though any of these three can be omitted (as well as step can be omitted since it defaults to 1).

delnan
A: 
In [24]: s = 'hello, world'

In [25]: tmp = [''.join(t) for t in zip(s[::2], s[1::2])]

In [26]: print tmp
['he', 'll', 'o,', ' w', 'or', 'ld']
ars
A: 
def str_split_like_php(s, n):
    """Split `s` into chunks `n` chars long."""
    ret = []
    for i in range(0, len(s), n):
        ret.append(s[i:i+n])
    return ret
Ned Batchelder
why not list comprehension?
SilentGhost
I guess I still think "natively" in loops, then optimize down to comprehensions later, and I skipped the second step!
Ned Batchelder