unreal4u
unreal4u

Reputation: 33

Looking for a PHP's str_split() replacement

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?

Upvotes: 1

Views: 1085

Answers (4)

SilentGhost
SilentGhost

Reputation: 319601

for i in range(0, len(the_string), 2):
    print(the_string[i:i+2])

Upvotes: 6

Ned Batchelder
Ned Batchelder

Reputation: 375594

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

Upvotes: 0

ars
ars

Reputation: 123518

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']

Upvotes: 0

user395760
user395760

Reputation:

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).

Upvotes: 3

Related Questions