itsource

Python 문자열에서 마지막 구분 기호로 분할하시겠습니까?

mycopycode 2022. 9. 17. 09:57
반응형

Python 문자열에서 마지막 구분 기호로 분할하시겠습니까?

문자열에서 딜리미터가 마지막으로 나타날 때 문자열을 분할할 때 권장되는 Python 관용구는 무엇입니까?예:

# instead of regular split
>> s = "a,b,c,d"
>> s.split(",")
>> ['a', 'b', 'c', 'd']

# ..split only on last occurrence of ',' in string:
>>> s.mysplit(s, -1)
>>> ['a,b,c', 'd']

mysplit는 분할할 딜리미터의 발생인두 번째 인수를 사용합니다.일반적인 목록 색인처럼-1끝에서부터의 마지막을 의미합니다.이것이 어떻게 행해지는가?

또는 대신 사용:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit()분할 횟수를 지정할 수 있습니다.str.rpartition()분할은 1회뿐이지만 항상 고정된 수의 요소(슬롯, 딜리미터 및 포스트픽스)를 반환하며 단일 분할 케이스에서 더 빠릅니다.

데모:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

두 메서드 모두 스트링의 오른쪽에서 분할을 시작합니다.str.rsplit()두 번째 인수로 maximum을 지정하면 오른쪽 끝에 있는 항목만 분할할 수 있습니다.

마지막 요소만 필요하지만 딜리미터가 입력 문자열에 없거나 입력의 마지막 문자일 가능성이 있는 경우 다음 식을 사용합니다.

# last element, or the original if no `,` is present or is the last character
s.rsplit(',', 1)[-1] or s
s.rpartition(',')[-1] or s

마지막 문자라도 딜리미터를 없애야 할 경우 다음을 사용합니다.

def last(string, delimiter):
    """Return the last element from string, after the delimiter

    If string ends in the delimiter or the delimiter is absent,
    returns the original string without the delimiter.

    """
    prefix, delim, last = string.rpartition(delimiter)
    return last if (delim and last) else prefix

이것은, 라는 사실을 이용한다.string.rpartition()는 딜리미터가 존재하는 경우에만 두 번째 인수로 반환되며, 그렇지 않은 경우에는 빈 문자열로 반환됩니다.

rsplit을 사용할 수 있습니다.

string.rsplit('delimeter',1)[1]

역행렬을 가져오다.

그냥 장난삼아 한 거야

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

주의:이 답변이 잘못될 수 있는 경우 아래의 첫 번째 주석을 참조하십시오.

언급URL : https://stackoverflow.com/questions/15012228/splitting-on-last-delimiter-in-python-string

반응형