这是我的一些代码:
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!!!
关于python - 在字符串切片中包含完整的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635855/