在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中迭代字符串?
今天早些时候,我需要一次迭代一个字符串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)
有没有更好/更清洁的方法来做到这一点?