在python中从字符串中获取两个字符

时间:2010-05-22 13:38:19

标签: python loops for-loop character

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

我有:

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

它让我喜欢

a
b
c
d

但我需要

ab
cd

我是python中的新手..有什么办法吗?

3 个答案:

答案 0 :(得分:11)

您可以使用切片表示法。 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)

答案 1 :(得分:7)

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)

答案 2 :(得分:-1)

我也是Python的新手,请看一下我的代码:

long_str = "abcdefghi"

state1=True
state2=False
state3=True

for item in long_str:
    if state1:
       print(item,end="")
       state3=True

    if state2:
       print(item)
       state1=True
       state2=False
       state3=False

    if state3:
       state1=False
       state2=True

输出:

ab
cd
ef
gh
i