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

标签 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 个字符。以一个词结尾,取整个词...?

最佳答案

包括电池:

>>> 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/

相关文章:

c++ - 在 C++ 中使用递归构建字符串

c - 当我们不知道数组的大小时,我们如何遍历整数数组?

python - Pandas 在设置输出目录时引发错误

javascript - 多行字符串 findIndex()

c - 添加数字并计算字符串的字母数(段错误)

scala - 从有状态算法创建 Enumeratee

C:不使用循环语句或递归的循环

python - Pandas : plot stacked barchart for row values

python - 如何在pytest中引发异常?

python - 如何找到列表交集?