Split a string into a list with parts of N characters [duplicate]

人走茶凉 提交于 2021-02-05 12:20:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!