2016-09-18 42 views
-1

我对python很陌生,想知道最简单的方法是将字符串拆分成N个字符的一部分。将一个字符串拆分成一个包含N个字符的部分的列表

我遇到这样的:

>>>s = "foobar" 
>>>list(s) 
['f', 'o', 'o', 'b', 'a', 'r'] 

这是我如何把字符串转换成字符的列表,但我想要的是有一个方法是这样的:

>>>def splitInNSizedParts(s, n): 

其中

>>>print(splitInNSizedParts('foobar', 2)) 
['fo', 'ob', 'ar'] 
+1

也有一些好的想法[这里](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate -over-a-list-in-chunks)和[here](http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character)。 –

回答

1
import textwrap 
print textwrap.wrap("foobar", 2) 

那么你的功能将是:

def splitInNSizedParts(s, n): 
    return textwrap.wrap(s, n) 
+0

谢谢!只是 textwrap.wrap(s,n) 会做! –

相关问题