Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Cut off the last word of a sentence?

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 reconcatenating the list.
  2. Use a regular expression to replace the last word.

I'm currently taking approach #1, but I don't know how to concatenate the list...

content = content[position-1:position+249] # Content words = string.split(content, ' ') words = words[len[words] -1] # Cut of the last word 

Any code examples are much appreciated.

like image 230
qwerty Avatar asked Jun 07 '11 14:06

qwerty


People also ask

How do you remove the last part of a string in Python?

Using rstrip() to remove the last character The rstrip() is a built-in Python function that returns a String copy with trailing characters removed. For example, we can use the rstrip() function with negative indexing to remove the final character of the string.

How do you cut a word out of a sentence in Python?

Remove a Word from String using replace() print("Enter String: ", end="") text = input() print("Enter a Word to Delete: ", end="") word = input() wordlist = text. split() if word in wordlist: text = text.

How do you remove the first and last words in Python?

Method #1: Using split() Method This task can be performed using the split function which performs a split of words and separates the first word of string with the entire words.

How do you cut a word in half in Python?

Use Newline (\n) Character In Python, the string is split by the use of the newline (\n) character.


2 Answers

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

like image 64
Roman Bodnarchuk Avatar answered Sep 20 '22 19:09

Roman Bodnarchuk


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.

like image 36
murgatroid99 Avatar answered Sep 22 '22 19:09

murgatroid99