5 ответов:
разделить на разделителе не более одного раза, и взять первый кусок:
sep = '...' rest = text.split(sep, 1)[0]вы не сказали, что должно произойти, если разделителя нет. И это, и решение Алекса вернут всю строку в этом случае.
предполагая, что ваш разделитель'...но это может быть любой строкой.
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
без огня (который я предполагаю, что это то, что вы хотите):
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)
еще один простой способ использования 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
Comments