Python: Cut off the last word of a sentence?

2019-01-22 17:21发布

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.

7条回答
我想做一个坏孩纸
2楼-- · 2019-01-22 18:13

OR

import re

print ' '.join(re.findall(r'\b\w+\b', text)[:-1])
查看更多
登录 后发表回答