有没有办法修剪字符串以在特定点开始和结束?
这是一个例子:我希望字符串(文本)在第一个完全停止后立即开始,并在最后一个完整停止时结束.
_string = "money is good. love is better. be lucky to have any. can't really have both"
Run Code Online (Sandbox Code Playgroud)
预期产量:
"love is better. be lucky to have any."
Run Code Online (Sandbox Code Playgroud)
我的尝试:
import re
pattern = "\.(?P<_string>.*?.*?).\"
match = re.search(pattern, _string)
if match != None:
print match.group("_string")
Run Code Online (Sandbox Code Playgroud)
我的尝试开始很好,但在第二个full_stop停了下来.
关于如何达到预期产量的任何想法?
如果字符串中至少有一个点,这将有效.
print _string[_string.index(".") + 1:_string.rindex(".") + 1]
# love is better. be lucky to have any.
Run Code Online (Sandbox Code Playgroud)
如果您不想在开头使用空格,那么您可以像这样剥离它
print _string[_string.index(".") + 1:_string.rindex(".") + 1].lstrip()
# love is better. be lucky to have any.
Run Code Online (Sandbox Code Playgroud)