2010-07-19 52 views
1

比方说,我有这小小的一段代码:寻找一个PHP的str_split()的替代

<?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); 
?> 

我怎样才能做到这一点在Python V2.7?

我认为这将做到这一点:

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

但它返回一个“空分离”的错误。

对此有何看法?

+0

我差点忘了,PHP对str_split文档: http://www.php.net/manual/es/function.str-split.php 在foreach循环中,我创建$作为参考传递,这是正确的,因为我之前在销毁它之前操纵$ tmp。 – unreal4u 2010-07-19 16:29:18

回答

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

或者返回一个列表:[s [x:x + 2]为x在范围内(0,len(s),2)] – twneale 2010-07-19 16:44:01

+0

谢谢,这当然没有诀窍:) – unreal4u 2010-07-19 16:47:53

2

tmp = the_string[::2]给出了每个第二个元素的the_string的副本。 ... [:: 1]会返回每个元素的副本,... [:: 3]会给每个第三个元素,等等。

请注意,这是一个切片,完整形式是list [start :stop:step],尽管这三个中的任何一个都可以省略(以及step可以省略,因为它默认为1)。

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

为什么不列出理解? – SilentGhost 2010-07-19 16:47:13

+0

我想我仍然认为“本地”在循环中,然后优化到稍后的理解,我跳过了第二步! – 2010-07-19 16:57:28