web-dev-qa-db-ja.com

Pythonで特定の文字の後のすべての文字を削除するにはどうすればよいですか?

文字列があります。特定の文字の後のすべてのテキストを削除するにはどうすればよいですか? (この場合は...
後のテキストは...に変更されるため、特定の文字の後のすべての文字を削除したいのです。

113
Solihull

セパレーターで最大1回分割し、最初のピースを取得します。

sep = '...'
rest = text.split(sep, 1)[0]

区切り文字が存在しない場合に何が起こるべきかは言わなかった。この場合、Alexのソリューションは両方とも、文字列全体を返します。

208
Ned Batchelder

区切り文字が「...」であると仮定しますが、任意の文字列を使用できます。

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

区切り文字が見つからない場合、headには元の文字列がすべて含まれます。

パーティション関数はPython 2.5で追加されました。

partition(...)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.
73
Ayman Hourieh

文字列内の最後のセパレータの出現後にすべてを削除したい場合、これはうまくいくことがわかります:

<separator>.join(string_to_split.split(<separator>)[:-1])

たとえば、string_to_splitroot/location/child/too_far.exeのようなパスで、フォルダーパスのみが必要な場合は、"/".join(string_to_split.split("/")[:-1])で分割でき、root/location/childを取得できます。

12
theannouncer

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)
9
Alex Martelli

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
0
Rohail