Skip to main content
 首页 » 编程设计

python之寻找 PHP 的 str_split() 替代品

2025年05月04日19kuangbin

假设我有这么一小段代码:

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

但它返回“空分隔符”错误。

对此有什么想法吗?

请您参考如下方法:

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