2016-09-18 41 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) 會做! –

相關問題