Split string into array with many char pro items
I have a string and I want an array of str for example:
"hello world"
["hel", "lo ", "wor", "ld"]
or
["hell", "o wo", "rld"]
I see that list(message)
would be ok but just for
["h", "e", "l", "l开发者_StackOverflow中文版", "o", " ", "w", "o", "r", "l", "d", ]
Any ideas?
>>> s = 'hello world'
>>> [s[i:i+3] for i in range(len(s)) if not i % 3]
['hel', 'lo ', 'wor', 'ld']
For a more general solution (i.e. custom-defined splits), try this function:
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)
Which produces the output:
['hel', 'lo ', 'wor', 'ld']
['hell', 'o w', 'orld']
OR if you're really in the mood for a one-liner:
def split_on_parts(s, *parts):
return [s[sum(parts[:p]):sum(parts[:p+1])] for p in range(len(parts))]
>>> 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']
>>> lst = ['he', 'llo', ' wo', 'rld']
>>> ''.join(lst)
'hello world'
>>> s = 'hello world'
>>> list(s)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Those are the basics; if you have any specific requirements, comment on this post and I'll update my answer.
`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']
>>> 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']
Not sure how (by what criteria) exactly it was meant to be split though.
精彩评论