What's the best way to slice the last word from a block of text?
I can think of
- Split it to a list (by spaces) and removing the last item, then reconcatenating the list.
- 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.
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):
This splits content into words, takes all but the last word, and rejoins the words with spaces.
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]
withwords = words[:-1]
to make use of list slicing.' '.join(words)
will put the list back together.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:
rsplit
is a shorthand for "reverse split", and unlike regularsplit
works from the end of a string. The second parameter is a maximum number of splits to make - e.g. value of1
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).Get last index of space and splice the string
If you like compactness: