这是我的一些代码:
def breakUp(x,chunk_size):
return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]
以下是它的工作原理:
In [8]: breakUp('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!',10)
Out[8]:
['This is a ',
'cool sente',
'nce... How',
' about eat',
'ing it??? ',
'Whats more',
'?? pepper ',
'is availab',
'le all for',
' free!!!']
但正如你在第二个元素中看到的,句子这个词并没有被完全采用,它说"sente"......
我知道这是因为我已经要求 python 每 10 个字符拆分一次......有没有指定我想在每 10 个字符之后拆分,但如果第 10 个字符以一个单词结尾,取整个单词......?
包括电池:
>>> import textwrap
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)
This is a cool
sentence... How
about eating
it??? Whats
more?? pepper
is available
all for free!!!
这几乎可以满足您的所有要求。 除了如果您将 10
指定为第二个参数,它仍将拆分sentence...
,因为无法将其容纳 10 个字符。 但是,如果要执行此操作,可以使用break_long_words=False
自定义textwrap
:
>>> print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 10, break_long_words=False)
This is a
cool
sentence...
How about
eating
it???
Whats
more??
pepper is
available
all for
free!!!