Python: Cut off the last word of a sentence?

家住魔仙堡 提交于 2019-11-28 20:05:16

Actually you don't need to split all words. You can split you text by last space symbol into two parts using rsplit.

Some example:

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut of the last word of a'

rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of 1 will give you two-element list as a result (since there was a single split made, which resulted in two pieces of the input string).

You should definitely split and then remove the last word because a regex will have both more complications and unnecessary overhead. You can use the more Pythonic code (assuming content is a string):

' '.join(content.split(' ')[:-1])

This splits content into words, takes all but the last word, and rejoins the words with spaces.

If you like compactness:

' '.join(content.split(' ')[:-1]) + ' ...'

If you want to keep your current method, use ' '.join(words) to concatenate the list.

You also might want to replace words = words[len[words -1] with words = words[:-1] to make use of list slicing.

' '.join(words) will put the list back together.

OR

import re

print ' '.join(re.findall(r'\b\w+\b', text)[:-1])

Get last index of space and splice the string

>>> text = 'Python: Cut of the last word of a sentence?'
>>> text[:text.rfind(' ')]
'Python: Cut of the last word of a'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!