我想在x字符后剪切一个长文本,但我不想在中间剪切一个单词,我想在x chars之前的最后一个空格处剪切:
'This is a sample text'[:20]
Run Code Online (Sandbox Code Playgroud)
给我
'This is a sample tex'
Run Code Online (Sandbox Code Playgroud)
但我想要
'This is a sample'
Run Code Online (Sandbox Code Playgroud)
另一个例子:
'And another sample sentence'[:15]
Run Code Online (Sandbox Code Playgroud)
给我
'And another sam'
Run Code Online (Sandbox Code Playgroud)
但我想要
'And another'
Run Code Online (Sandbox Code Playgroud)
最简单的方法是什么?
Ste*_*nes 20
import textwrap
lines = textwrap.wrap(text, 20)
# then use either
lines[0]
# or
'\n'.join(lines)
Run Code Online (Sandbox Code Playgroud)
您可以使用str.rpartition()或str.rsplit()删除余数的最后一个空格后的所有内容:
example[:20].rpartition(' ')[0]
example[:20].rsplit(' ', 1)[0]
Run Code Online (Sandbox Code Playgroud)
第二个参数用于str.rsplit()将拆分限制为从右侧开始的第一个空间,[0]索引采用在该空间之前拆分的任何内容.
str.rpartition()有点快,总是返回三个字符串; 如果没有空格,那么返回的第一个字符串是空的,所以你可能想要坚持,str.rsplit()如果这是可能的(在那种情况下该版本将返回一个包含单个字符串的列表,所以你最终再次使用原始字符串).
现在到了2022 年,我发现Steve 非常感谢地推荐的textwrapstdlibs 中有一个完全满足这种需求的方法:textwrap.shorten()。
>>> import textwrap
>>> textwrap.shorten("This is a sample text", width=20, placeholder="")
'This is a sample'
Run Code Online (Sandbox Code Playgroud)
它是在 Python 3.6 之前引入的,因此现在应该在大多数项目中可用。