在字符串切片中包含完整的单词

ten*_*tar 4 python string loops

这是我的一些代码:

def breakUp(x,chunk_size):
    return [ x[i:i+chunk_size] for i in range(0, len(x), chunk_size) ]
Run Code Online (Sandbox Code Playgroud)

这是它的工作原理:

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!!!']
Run Code Online (Sandbox Code Playgroud)

但正如你在第二个元素中所看到的那样,单词句子没有被完全采用,它说"sente"......

我知道这是因为我已经要求python将其拆分为每10个字符...无论如何指定我想在每10个字符之后拆分但是如果是第10个字符.一言以蔽之,全拿一字......?

Rom*_*huk 6

电池包括:

>>> 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!!!
Run Code Online (Sandbox Code Playgroud)

这几乎就是你所要求的.除非您指定10为第二个参数,否则它仍会分割,sentence...因为无法将其组合为10个字符.但是,如果要执行此操作,可以textwrap使用break_long_words=False以下命令进行自定义:

>>> 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!!!
Run Code Online (Sandbox Code Playgroud)