相关疑难解决方法(0)

使用Python迭代字符串中的每个字符

在C++中,我可以迭代std::string这样:

std::string str = "Hello World!";

for (int i = 0; i < str.length(); ++i)
{
    std::cout << str[i] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如何在Python中迭代字符串?

python string iteration

502
推荐指数
6
解决办法
62万
查看次数

在Python中一次迭代字符串2(或n)个字符

今天早些时候,我需要一次迭代一个字符串2个字符来解析格式化的字符串"+c-R+D-E"(有一些额外的字母).

我最终得到了这个,但它看起来很难看.我最后评论它正在做什么,因为它感觉不明显.它几乎似乎是pythonic,但并不完全.

# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
  print op, code
Run Code Online (Sandbox Code Playgroud)

有没有更好/更清洁的方法来做到这一点?

python iteration

32
推荐指数
5
解决办法
3万
查看次数

标签 统计

iteration ×2

python ×2

string ×1