如何删除所有在python中的特定字符后的字符?
我有一个string。 如何删除特定字符后的所有文本?  ( 在这种情况下... ) 
 后面的文字将会改变,所以我这就是为什么我想删除所有字符后,一个特定的。 
最多分开一次,拿第一块:
 sep = '...' rest = text.split(sep, 1)[0] 
你没有说如果分离器不存在会发生什么。 在这种情况下,这个和Alex的解决scheme将返回整个string。
假设你的分隔符是'…',但它可以是任何string。
 text = 'some string... this part will be removed.' head, sep, tail = text.partition('...') >>> print head some string 
 如果没有find分隔符, head将包含所有原始string。 
分区函数是在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.
没有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) 
如果你想在string中最后一个分隔符出现后删除所有的东西,我觉得这个效果很好:
 <separator>.join(string_to_split.split(<separator>)[:-1]) 
 例如,如果string_to_split是一个像root/location/child/too_far.exe的path,而你只想要文件夹path,那么可以用"/".join(string_to_split.split("/")[:-1])来分割。你会得到root/location/child 
使用re的另一个简单的方法是
 import re, clr text = 'some string... this part will be removed.' text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1) // text = some string