将字符串拆分为包含许多char项目的数组

时间:2010-12-09 19:43:56

标签: python string function split

我有一个字符串,我想要一个例如str的数组:

"hello world"
["hel", "lo ", "wor", "ld"]

["hell", "o wo", "rld"]

我看到list(message)可以,但仅适用于

["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ]

有什么想法吗?

5 个答案:

答案 0 :(得分:3)

>>> s = 'hello world'
>>> [s[i:i+3] for i in range(len(s)) if not i % 3]
['hel', 'lo ', 'wor', 'ld']

对于更通用的解决方案(即自定义分割),请尝试以下函数:

def split_on_parts(s, *parts):
    total = 0
    buildstr = []
    for p in parts:
        buildstr.append(s[total:total+p])
        total += p
    return buildstr

s = 'hello world'
print split_on_parts(s, 3, 3, 3, 3)
print split_on_parts(s, 4, 3, 4)

产生输出:

['hel', 'lo ', 'wor', 'ld']
['hell', 'o w', 'orld']

如果你真的想要一个单行的话:

def split_on_parts(s, *parts):
    return [s[sum(parts[:p]):sum(parts[:p+1])] for p in range(len(parts))]

答案 1 :(得分:3)

>>> def split_length(s, l):
...     return [s[i:i+l] for i in range(0, len(s), l)]
... 
>>> split_length("hello world", 3)
['hel', 'lo ', 'wor', 'ld']
>>> split_length("hello world", 4)
['hell', 'o wo', 'rld']

答案 2 :(得分:2)

>>> lst = ['he', 'llo', ' wo', 'rld']
>>> ''.join(lst)
'hello world'
>>> s = 'hello world'
>>> list(s)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

这些是基础知识;如果您有任何具体要求,请对此帖发表评论,我会更新我的答案。

答案 3 :(得分:1)

`list` is a python key word. You can use list and indexing power of list to manipulate your result.

In [5]: s = 'hello world'

In [6]: s.split()
Out[6]: ['hello', 'world']

In [7]: list(s)
Out[7]: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

答案 4 :(得分:0)

>>> s
'hello world'
>>> filter(lambda n: n != ' ', re.split("(o|wo)", s))
['hell', 'o', 'wo', 'rld']
>>> filter(lambda n: n != ' ', re.split("(lo|wor)", s))
['hel', 'lo', 'wor', 'ld']

不确定(按什么标准)究竟是什么意思被拆分。