Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中从字符串中获取两个字符_Python_Loops_For Loop_Character - Fatal编程技术网

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

在python中从字符串中获取两个字符,python,loops,for-loop,character,Python,Loops,For Loop,Character,在python中,如何从字符串(不是一个字符,而是两个字符)获取数据 我有: long_str = 'abcd' for c in long_str: print c 这让我感觉 a b c d 但我需要得到 ab cd 我是python新手。。有什么办法吗?您可以使用切片表示法long_str[x:y]将为您提供范围[x,y)内的字符(其中包括x,不包括y) 在这里,我使用三参数范围运算符来表示开始、结束和步骤(请参阅) 请注意,对于长度为奇数的字符串,这将不使用最后一个字符。如果

在python中,如何从字符串(不是一个字符,而是两个字符)获取数据

我有:

long_str = 'abcd'
for c in long_str:
   print c
这让我感觉

a
b
c
d
但我需要得到

ab
cd

我是python新手。。有什么办法吗?

您可以使用切片表示法
long_str[x:y]
将为您提供范围
[x,y)
内的字符(其中包括x,不包括y)

在这里,我使用三参数范围运算符来表示开始、结束和步骤(请参阅)

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


还提供了这方面的一般实现:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
“什么是最“pythonic”的方式来迭代一个列表中的块?”
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)
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)