2010-07-19 123 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