[python] 문자열에서 선행 및 후행 0을 제거하는 방법은 무엇입니까? 파이썬

이와 같은 영숫자 문자열이 여러 개 있습니다.

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', '000alphanumeric']

후행 0 을 제거하기 위해 원하는 출력 은 다음과 같습니다.

listOfNum = ['000231512-n','1209123100000-n','alphanumeric', '000alphanumeric']

선행 후행 0에 대한 원하는 출력 은 다음과 같습니다.

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']

선행 및 후행 0을 모두 제거하기위한 원하는 출력은 다음과 같습니다.

listOfNum = ['231512-n','1209123100000-n', 'alphanumeric', 'alphanumeric']

지금은 다음과 같은 방법으로 해왔습니다.있는 경우 더 나은 방법을 제안하십시오.

listOfNum = ['000231512-n','1209123100000-n00000','alphanumeric0000', \
'000alphanumeric']
trailingremoved = []
leadingremoved = []
bothremoved = []

# Remove trailing
for i in listOfNum:
  while i[-1] == "0":
    i = i[:-1]
  trailingremoved.append(i)

# Remove leading
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  leadingremoved.append(i)

# Remove both
for i in listOfNum:
  while i[0] == "0":
    i = i[1:]
  while i[-1] == "0":
    i = i[:-1]
  bothremoved.append(i)



답변

기본은 어떻습니까

your_string.strip("0")

후행 및 선행 0을 모두 제거하려면? 후행 0을 제거하는 데만 관심이있는 경우 .rstrip대신 사용하십시오 (그리고 선행 0 .lstrip에만).

[ 문서에 더 많은 정보가 있습니다.]

목록 이해력을 사용하여 원하는 시퀀스를 얻을 수 있습니다.

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]


답변

선행 + 후행 ‘0’제거 :

list = [i.strip('0') for i in listOfNum ]

선행 ‘0’제거 :

list = [ i.lstrip('0') for i in listOfNum ]

후행 ‘0’제거 :

list = [ i.rstrip('0') for i in listOfNum ]


답변

bool로 간단히 할 수 있습니다.

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)


답변

당신과 함께 시도해 봤어 ) (스트립 :

listOfNum = ['231512-n','1209123100000-n00000','alphanumeric0000', 'alphanumeric']
print [item.strip('0') for item in listOfNum]

>>> ['231512-n', '1209123100000-n', 'alphanumeric', 'alphanumeric']


답변

str.strip이 상황에 가장 적합한 접근 방식이지만 more_itertools.strip반복 가능한 요소에서 선행 및 후행 요소를 모두 제거하는 일반적인 솔루션이기도합니다.

암호

import more_itertools as mit


iterables = ["231512-n\n","  12091231000-n00000","alphanum0000", "00alphanum"]
pred = lambda x: x in {"0", "\n", " "}
list("".join(mit.strip(i, pred)) for i in iterables)
# ['231512-n', '12091231000-n', 'alphanum', 'alphanum']

세부

여기서 우리 "0"는 술어를 만족하는 다른 요소들 사이에서 선행 및 후행 s를 모두 제거합니다 . 이 도구는 문자열에만 국한되지 않습니다.

더 많은 예제는 문서를 참조하십시오.

more_itertools을 통해 설치할 수있는 타사 라이브러리 > pip install more_itertools입니다.


답변

목록에 다른 데이터 유형 (문자열뿐만 아니라)이 있다고 가정 해보십시오. 이렇게하면 문자열에서 후행 및 선행 0이 제거되고 다른 데이터 유형은 그대로 유지됩니다. 이것은 또한 특별한 경우 s = ‘0’을 처리합니다.

예 :

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']


답변