在Python中从字符串中获取两个字符 [英] Getting two characters from string in python

查看:1379
本文介绍了在Python中从字符串中获取两个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to get in python from string not one character, but two?

我有:

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

它给了我像

a
b
c
d

但是我需要得到

ab
cd

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

I'm new in python.. is there any way?

推荐答案

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 也对此提供了通用的实现:


itertools also provide a generalized implementation of this:

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

这篇关于在Python中从字符串中获取两个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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