问题
I'm very new to python and was wondering what the most pythonic/easy way is to split a string into a list with parts of N characters.
I've come across this:
>>>s = "foobar"
>>>list(s)
['f', 'o', 'o', 'b', 'a', 'r']
which is how I can turn a string into a list of characters, but what I would want is to have a method that would look like this:
>>>def splitInNSizedParts(s, n):
where
>>>print(splitInNSizedParts('foobar', 2))
['fo', 'ob', 'ar']
回答1:
import textwrap
print textwrap.wrap("foobar", 2)
Then your function will be :
def splitInNSizedParts(s, n):
return textwrap.wrap(s, n)
来源:https://stackoverflow.com/questions/39556512/split-a-string-into-a-list-with-parts-of-n-characters