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

标签 python string

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

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

关于python - 寻找 PHP 的 str_split() 替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3282929/

相关文章:

python - 使用 [ ] 而不是点访问 Dataframe 列时出现 Pandas 'SettingsWithCopyWarning'

python - 如何设置特定长度的特定 faker 随机字符串并使用下划线作为空格?

C# string.Format 1000,00 到 1.000,00

python - url django 中渲染的 slugs 不正确

python - Matplotlib:获取子图以填充图形

python - 导入作为符号链接(symbolic link)的文件

java - 字符串比较没有跳出 while 循环

string - 如何使用 Boost::asio 异步读取 std::string?

php - 将 C(\0 终止)字符串转换为 PHP 字符串

database - 如何使用 MS SQL 查找带括号的字符串的最后一部分