Truncate a string without ending in the middle of a word

后端 未结 8 1821
无人共我
无人共我 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:49

    Here's a slightly better version of the last line in Adam's solution:

    return content[:length].rsplit(' ', 1)[0]+suffix
    

    (This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.)

提交回复
热议问题