Truncate a string without ending in the middle of a word

后端 未结 8 1834
无人共我
无人共我 2020-12-12 17:17

I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.

For example:

Original:          \"This is          


        
8条回答
  •  忘掉有多难
    2020-12-12 17:41

    From Python 3.4+ you can use textwrap.shorten. With the OP example:

    >>> import textwrap
    >>> original = "This is really awesome."
    >>> textwrap.shorten(original, width=20, placeholder="...")
    'This is really...'
    

    textwrap.shorten(text, width, **kwargs)

    Collapse and truncate the given text to fit in the given width.

    First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width:

提交回复
热议问题