Truncate a string without ending in the middle of a word

后端 未结 8 1812
无人共我
无人共我 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...'
    
    0 讨论(0)
  • 2020-12-12 18:03

    For Python 3.4+, I'd use textwrap.shorten.

    For older versions:

    def truncate(description, max_len=140, suffix='…'):    
        description = description.strip()
        if len(description) <= max_len:
            return description
        new_description = ''
        for word in description.split(' '):
          tmp_description = new_description + word
          if len(tmp_description) <= max_len-len(suffix):
              new_description = tmp_description + ' '
          else:
              new_description = new_description.strip() + suffix
              break
        return new_description
    
    0 讨论(0)
提交回复
热议问题