将字符串拆分为列表,且列表项的长度相等 [英] Split string into a list, with items of equal length
本文介绍了将字符串拆分为列表,且列表项的长度相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串(无空格),我需要将其拆分为长度相等的项目列表.我知道split()
方法,但是据我所知,它仅通过空格而不是长度进行分割.
I have a string (without spaces) which I need to split into a list with items of equal length. I'm aware of the split()
method, but as far as I'm aware this only splits via spaces and not via length.
我想做的是这样的:
string = "abcdefghijklmnopqrstuvwx"
string = string.Split(0 - 3)
print(string)
>>> ["abcd", "efgh", "ijkl", "mnop", "qrst", "uvwx"]
我曾考虑过遍历列表,但我想知道是否有一个更简单的解决方案?
I have thought about looping through the list but I was wondering if there was a simpler solution?
推荐答案
>>> [string[start:start+4] for start in xrange(0, len(string), 4)]
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']
即使最后一块少于4个字符,它也可以工作.
It works even if the last piece has less than 4 characters.
这篇关于将字符串拆分为列表,且列表项的长度相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文