ProgramingTip

python : 어디에서 어디에서나 어디에서나 어디에서나 제거됩니다.

bestdevel 2020. 12. 29. 07:45
반응형

python : 어디에서 어디에서나 어디에서나 어디에서나 제거됩니다.


나는 많은 줄이있다

그들 중 일부는 ' rec'

마지막 4자인 경우에만 제거하고 싶습니다.

그래서 다른 말

somestring='this is some string rec'

나는 그것을 원한다 :

somestring='this is some string'

이것에 접근하는 방법은 무엇입니까?


def rchop(thestring, ending):
  if thestring.endswith(ending):
    return thestring[:-len(ending)]
  return thestring

somestring = rchop(somestring, ' rec')

당신이 필요한 것이 있기 때문에 len(trailing)(여기서는 trailing당신이있는 경우에 제거 할 수 있습니다) 나는 작품의 약간의 원인 .endswith이 있습니다. 물론 코드의 증거는 타이밍에 따라서 몇 가지 측정을 수행해 보겠습니다 (응답 제안한 함수 이름 지정).

import re

astring = 'this is some string rec'
trailing = ' rec'

def andrew(astring=astring, trailing=trailing):
    regex = r'(.*)%s$' % re.escape(trailing)
    return re.sub(regex, r'\1', astring)

def jack0(astring=astring, trailing=trailing):
    if astring.endswith(trailing):
        return astring[:-len(trailing)]
    return astring

def jack1(astring=astring, trailing=trailing):
    regex = r'%s$' % re.escape(trailing)
    return re.sub(regex, '', astring)

def alex(astring=astring, trailing=trailing):
    thelen = len(trailing)
    if astring[-thelen:] == trailing:
        return astring[:-thelen]
    return astring

이 설치 파일의 이름을 지정 a.py하세요 현재 디렉토리에 가정 해 보겠습니다 . 지금, ... :

$ python2.6 -mtimeit -s'import a' 'a.andrew()'
100000 loops, best of 3: 19 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack0()'
1000000 loops, best of 3: 0.564 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack1()'
100000 loops, best of 3: 9.83 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.alex()'
1000000 loops, best of 3: 0.479 usec per loop

보시다시피, RE 기반 솔루션은 "절망적으로 능가"합니다 (한 사람이 문제를 "과도하게 처리"할 때 자주 발생합니다. 아마도 RE가 Python 커뮤니티에서 그렇게 나쁜 담당자를위한 이유 중 하나 일 수 있습니다!-) . @Jack의 의견은 @Andrew의 원본보다 훨씬 낫습니다. 예상대로 확장 기반 솔루션은 endswith@Jack보다 약간의 이점이 있습니다 (15 % 더 빠름). (어떤 사람은 약간의 변형을 선호합니다.)-어떤 사람은 약간의 변형을 선호합니다. . "낭비가 보유 부족이 없다"!-)


속도가 중요하지 않은 경우 정규식을 사용하십시오.

import re

somestring='this is some string rec'

somestring = re.sub(' rec$', '', somestring)

정규식을 사용할 수도 있습니다.

from re import sub

str = r"this is some string rec"
regex = r"(.*)\srec$"
print sub(regex, r"\1", str)

다음은 형제와 함께 Jack Kelly의 답변을 한 줄로 표현한 것입니다.

def rchop(s, sub):
    return s[:-len(sub)] if s.endswith(sub) else s

def lchop(s, sub):
    return s[len(sub):] if s.startswith(sub) else s

하나의 라이너 생성기가 결합 된 것과 같이 :

test = """somestring='this is some string rec'
this is some string in the end word rec
This has not the word."""
match = 'rec'
print('\n'.join((line[:-len(match)] if line.endswith(match) else line)
      for line in test.splitlines()))
""" Output:
somestring='this is some string rec'
this is some string in the end word 
This has not the word.
"""

사용하다:

somestring.rsplit(' rec')[0]

를 사용 하여 술어를 전달하는 문자열을 more_itertools사용할 수 있습니다 rstrip.

설치

> pip install more_itertools

암호

import more_itertools as mit


iterable = "this is some string rec".split()
" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
# 'this is some string'

" ".join(mit.rstrip(iterable, pred=lambda x: x in {"rec", " "}))
# 'this is some string'

여기서 우리는 끝에서 제거하려는 모든 후행 항목을 전달합니다.

자세한 내용은 more_itertools문서 를 참조하십시오.


에서 영감을 촬영 @ 데이빗 포스터 (David Foster) 의 대답은 , 내가 할 것

def _remove_suffix(text, suffix):
    if text is not None and suffix is not None:
        return text[:-len(suffix)] if text.endswith(suffix) else text
    else:
        return text

참조 : Python문자열 슬라이싱



def remove_trailing_string(content, trailing):
    """
    Strip trailing component `trailing` from `content` if it exists.
    """
    if content.endswith(trailing) and content != trailing:
        return content[:-len(trailing)]
    return content

참조 URL : https://stackoverflow.com/questions/3663450/python-remove-substring-only-at-the-end-of-string

반응형