Split python string every nth character iterating

2019-07-29 08:37发布

I'm trying to find an elegant way to split a python string every nth character, iterating over which character to start with.

For example, suppose I have a string containing the following:

ANDTLGY

I want to split the string into a set of 3 characters looking like this:

['AND','NDT','DTL','TLG','LGY']

3条回答
对你真心纯属浪费
2楼-- · 2019-07-29 08:40

how about

a='ANDTLGY'

def chopper(s,chop=3):
     if len(s) < chop:
        return []
     return [s[0:chop]] + chopper(s[1:],chop)

this returns

['AND', 'NDT', 'DTL', 'TLG', 'LGY']
查看更多
forever°为你锁心
3楼-- · 2019-07-29 08:42
a='ANDTLGY'
def nlength_parts(a,n):
    return map(''.join,zip(*[a[i:] for i in range(n)]))

print nlength_parts(a,3)

hopefully you can explain to the professor how it works ;)

查看更多
【Aperson】
4楼-- · 2019-07-29 08:43

Simple way is to use string slicing together with list comprehensions:

s = 'ANDTLGY'
[s[i:i+3] for i in range(len(s)-2)]
#output:
['AND', 'NDT', 'DTL', 'TLG', 'LGY']
查看更多
登录 后发表回答