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

时间:2013-10-28 13:16:39

标签: python string loops

这是我的一些代码:

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个字符。一言以蔽之,全拿一字......?

1 个答案:

答案 0 :(得分: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!!!

这几乎就是你所要求的。除非您将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!!!