在Python中一次遍历字符串2(或n)个字符

2024-04-19 03:46:40 发布

您现在位置:Python中文网/ 问答频道 /正文

今天早些时候,我需要一次遍历一个字符串2个字符来解析格式类似"+c-R+D-E"的字符串(还有一些额外的字母)。

我最终得到了这个,这很管用,但看起来很难看。我最后评论了它在做什么,因为它感觉不明显。看起来像是Python,但不完全是。

# 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

有没有更好/更干净的方法来做这个?


Tags: the字符串infor格式字母评论not
3条回答

Triptych启发了这个更一般的解决方案:

def slicen(s, n, truncate=False):
    assert n > 0
    while len(s) >= n:
        yield s[:n]
        s = s[n:]
    if len(s) and not truncate:
        yield s

for op, code in slicen("+c-R+D-e", 2):
    print op,code

不知道清洁剂,但还有另一个选择:

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

也许这会更干净?

s = "+c-R+D-e"
for i in xrange(0, len(s), 2):
    op, code = s[i:i+2]
    print op, code

你也许可以写一个生成器来做你想做的事情,也许那会更像是Python:)

相关问题 更多 >