将字符串拆分为包含 N 个字符部分的列表 [英] Split a string into a list with parts of N characters

查看:60
本文介绍了将字符串拆分为包含 N 个字符部分的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 非常陌生,想知道最 pythonic/简单的方法是将字符串拆分为包含 N 个字符部分的列表.

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.

我遇到过这个:

>>>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):

哪里

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

推荐答案

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

那么你的函数将是:

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

这篇关于将字符串拆分为包含 N 个字符部分的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆