在python中使用指定步骤拆分字符串

时间:2016-10-15 13:18:01

标签: python string

我在python中有一个没有空格的字符串,我想让python每隔3个字母拆分这个字符串,就像'antlapcap'一样, 例如['ant', 'lap', 'cap']有没有办法做到这一点?

3 个答案:

答案 0 :(得分:0)

不确定这是否是一种更有效的方法 ,尝试:

string = "antlapcap"
list = []
i = 0
for i in range(i,len(string)):
    word =string[i:i+3] 
    list.append(word)
    i=i+3
j = list
b =j[::3]
print(b)

答案 1 :(得分:0)

迭代字符串,添加到字符串变量直到达到一定长度,然后将字符串附加到列表中。例如

def split_at_nth(string, split_size):
    s = ''
    res = []
    for char in string:
        s += char
        if len(s) == split_size:
            res.append(s)
            s = ''
    return res

s = 'antlapcap'
print(split_at_nth(s, 3)) # prints ['ant', 'lap', 'cap']

另一个选择是使用一系列列表推导:

def split_at_nth(string, split_size):
    res = [c for c in string]
    res = [sub for sub in zip(*[iter(res)]*3)]
    res = [''.join(tup) for tup in res]
    return res

s = 'antlapcap'
print(split_at_nth(s, 3)) # prints ['ant', 'lap', 'cap']

答案 2 :(得分:0)

这是一种简单的方法。

>>> a="abcdefghi"
>>> x=[]
>>> while len(a) != 0:
...  x.append(a[:3])
...  a=a[3:]
... 
>>> a
''
>>> x
['abc', 'def', 'ghi']

这只是将x列在字符a的前3个字符中,然后将a重新定义为a中的所有内容,但前3个字符除外直到a用完为止。

向用户@vlk(Split python string every nth character?)提供帽子提示,虽然我更改了while声明