Python: Cut off the last word of a sentence?

后端 未结 7 1540
攒了一身酷
攒了一身酷 2020-12-08 09:17

What\'s the best way to slice the last word from a block of text?

I can think of

  1. Split it to a list (by spaces) and removing the last item, then reco
7条回答
  •  再見小時候
    2020-12-08 09:50

    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).

提交回复
热议问题