2010-05-22 77 views
5

如何从字符串中获取python不是一个字符,而是两个?在Python中从字符串中获取两个字符

我:

long_str = 'abcd' 
for c in long_str: 
    print c 

,这让我像

a 
b 
c 
d 

,但我需要得到

ab 
cd 

我在蟒蛇新..有什么办法?

+0

有关“什么是最‘Python化’的方式来遍历在块列表?” http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – jfs 2010-05-22 20:06:59

回答

6
for i, j in zip(long_str[::2], long_str[1::2]): 
    print (i+j) 

import operator 
for s in map(operator.add, long_str[::2], long_str[1::2]): 
    print (s) 

itertools还提供了通用实现这一点:

def grouper(n, iterable, fillvalue=None): 
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return izip_longest(fillvalue=fillvalue, *args) 
+0

非常感谢你:) – Adomas 2010-05-22 13:49:08

10

您可以使用切片符号。 long_str[x:y]会为您提供[x, y)范围内的字符(其中x包含,y不包含)。

>>> for i in range(0, len(long_str) - 1, 2): 
... print long_str[i:i+2] 
... 
ab 
cd 

在这里,我使用三个参数的范围运算符来表示开始,结束,并且步骤(见http://docs.python.org/library/functions.html)。

请注意,对于奇数长度的字符串,这不会占用最后一个字符。如果您想要自己的最后一个字符,请将range的第二个参数更改为len(long_str)

+0

非常感谢你:) – Adomas 2010-05-22 13:44:12

+0

不客气!如果您发现它是最有帮助的答案,请将答案标记为已接受。 – danben 2010-05-22 15:35:08

+0

我忘了这个! – juniorRubyist 2017-06-23 00:02:36

相关问题