Answers:
假设分隔符为“ ...”,但它可以是任何字符串。
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
如果找不到分隔符,head
将包含所有原始字符串。
分区功能是在Python 2.5中添加的。
分区(...)S.partition(sep)->(head,sep,tail)
Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings.
如果要删除字符串中最后一次出现分隔符之后的所有内容,我会发现这很有效:
<separator>.join(string_to_split.split(<separator>)[:-1])
例如,如果 string_to_split
是像一个路径root/location/child/too_far.exe
,你只需要在文件夹路径,您可以通过拆分"/".join(string_to_split.split("/")[:-1])
,你会得到
root/location/child
没有RE(我想是您想要的):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
或者,使用RE:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
import re
test = "This is a test...we should not be able to see this"
res = re.sub(r'\.\.\..*',"",test)
print(res)
输出:“这是一个测试”
从文件中:
import re
sep = '...'
with open("requirements.txt") as file_in:
lines = []
for line in file_in:
res = line.split(sep, 1)[0]
print(res)