在Python中一次迭代一个字符串2(或n)个字符 [英] Iterate over a string 2 (or n) characters at a time in Python

查看:633
本文介绍了在Python中一次迭代一个字符串2(或n)个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早些时候,我需要一次迭代一个字符串2个字符来解析格式为+ c-R + DE的字符串(还有一些额外的字母)。

Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like "+c-R+D-E" (there are a few extra letters).

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

I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.

# 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

有更好/更清洁的方法吗?

Are there some better/cleaner ways to do this?

推荐答案

关于清洁的Dunno,但还有另一种选择:

Dunno about cleaner, but there's another alternative:

for (op, code) in zip(s[0::2], s[1::2]):
    print op, code

无复制版本:

from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
    print op, code

这篇关于在Python中一次迭代一个字符串2(或n)个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆