Python: Cut off the last word of a sentence?

PythonSplitConcatenationWordText Segmentation

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Example:

>>> text = 'Python: Cut off the last word of a sentence?'
>>> text.rsplit(' ', 1)[0]
'Python: Cut off 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).

Solution 2 - Python

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.

Solution 3 - Python

If you like compactness:

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

Solution 4 - Python

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.

Solution 5 - Python

OR

import re

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

Solution 6 - Python

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'

Solution 7 - Python

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

Solution 8 - Python

        
def replace_ending(sentence, old, new):
	S1 = sentence
	O1 = old
	N1 = new
    # Check if the old string is at the end of the sentence 
	if O1 in S1:
		# Using i as the slicing index, combine the part
		# of the sentence up to the matched string at the 
		# end with the new string
		i = S1.rsplit(' ',1)[0] + str(" ") + N1		
		new_sentence = i
		return new_sentence

	# Return the original sentence if there is no match 
	return sentence
	
print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"

Solution 9 - Python

Enother variant is to use an argument "args*"

For example:

def truncate_sentences(length, *sentences):
  for sentence in sentences:
    print(sentence[:length])

#call function

truncate_sentences(8, "What's going on here", "Looks like we've been cut off")

Would output:

"What's g"
"Looks li"

Let’s break this down:

  1. We have two parameters that our function truncate_sentences() defines. The first is a length parameter that will specify how many characters we want to keep. The second is a parameter called sentences that is paired with the unpacking operator, signifying it will take a variable number of arguments.
  2. On each iteration of the function, we are looping through the tuple created by the sentences argument (because it is paired with the unpacking operator) and perform a slice on the sentence based on the provided length argument. This forces every value in the sentences tuple to be cut down in length.

Solution 10 - Python

Try Below,

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
if sentence.endswith(old):
	# Using i as the slicing index, combine the part
	# of the sentence up to the matched string at the 
	# end with the new string
	i = sentence.rsplit(' ',1)[0] + str(" ")
	new_sentence = i + new
	return new_sentence

# Return the original sentence if there is no match 
return sentence

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionqwertyView Question on Stackoverflow
Solution 1 - PythonRoman BodnarchukView Answer on Stackoverflow
Solution 2 - Pythonmurgatroid99View Answer on Stackoverflow
Solution 3 - PythonGiacomo d'AntonioView Answer on Stackoverflow
Solution 4 - PythonNickAldwinView Answer on Stackoverflow
Solution 5 - PythonArtsiom RudzenkaView Answer on Stackoverflow
Solution 6 - PythonVikram Singh ChandelView Answer on Stackoverflow
Solution 7 - PythonWoobleView Answer on Stackoverflow
Solution 8 - PythonentryLVL-py3GuyView Answer on Stackoverflow
Solution 9 - PythonPobaranchukView Answer on Stackoverflow
Solution 10 - PythonjohnmistView Answer on Stackoverflow