有没有办法修剪字符串以在特定点开始和结束?
这是一个例子:我希望字符串(文本)在第一个完整停止后立即开始,并在最后一个完整停止时结束。
_string = "money is good. love is better. be lucky to have any. can't really have both"
预期产出:
"love is better. be lucky to have any."
我的尝试:
import re
pattern = "\.(?P<_string>.*?.*?).\"
match = re.search(pattern, _string)
if match != None:
print match.group("_string")
我的尝试开始很好,但在第二个full_stop停止了。
有关如何达到预期输出的任何想法?
答案 0 :(得分:5)
如果字符串中至少有一个点,这将有效。
print _string[_string.index(".") + 1:_string.rindex(".") + 1]
# love is better. be lucky to have any.
如果您不想要开头的空格,那么您可以像这样删除
print _string[_string.index(".") + 1:_string.rindex(".") + 1].lstrip()
# love is better. be lucky to have any.
答案 1 :(得分:2)
import re
_string = "money is good. love is better. be lucky to have any. can't really have both"
str1 =_string[_string.find(".")+1:]
for i in range(len(str1)-1,0,-1):
if(str1[i]=='.'):
a=str1[:i+1]
break
print a
#love is better. be lucky to have any.
答案 2 :(得分:1)
如何使用.index()
和.rindex()
方法进行字符串切片?
string = "money is good. love is better. be lucky to have any. can't really have both"
first_full_stop = string.index('.')
last_full_stop = string.rindex('.')
string = string[first_full_stop+1:last_full_stop+1]
或者你可以按句号分割(这个可以使用任意数量的句号):
string = "money is good. love is better. be lucky to have any. can't really have both"
string = string.split('.')
string = string[1:-1]
答案 3 :(得分:0)
正则表达式应该是:
\.(.*\.)
这将捕获第一个和最后一个newline
.
之外的所有文字
说明:
\. matches the character . literally
1st Capturing group (.*\.)
.* matches any character (except newline)
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\. matches the character . literally
如果您不想要开头的空间,请使用以下空格:
\.\s(.*\.)
希望这会有所帮助。