Truncate a string without ending in the middle of a word

后端 未结 8 1810
无人共我
无人共我 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 18:03

    def smart_truncate(s, width):
        if s[width].isspace():
            return s[0:width];
        else:
            return s[0:width].rsplit(None, 1)[0]
    

    Testing it:

    >>> smart_truncate('The quick brown fox jumped over the lazy dog.', 23) + "..."
    'The quick brown fox...'
    

提交回复
热议问题