这是我的一些代码:
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作为第二个参数,它仍然会拆分句子……因为没有办法让它适合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!!!
标签:python,loops,string