IT story

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

hot-time 2020. 9. 4. 08:09
반응형

문자열에서 선행 및 후행 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-n00000','alphanumeric0000', '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 ]

Remove trailing '0':

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

You can simply do this with a bool:

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

   number = int(number)

else:

   number = float(number)

Did you try with strip() :

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

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

str.strip is the best approach for this situation, but more_itertools.strip is also a general solution that strips both leading and trailing elements from an iterable:

Code

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']

Details

Notice, here we strip both leading and trailing "0"s among other elements that satisfy a predicate. This tool is not limited to strings.

See also docs for more examples of

more_itertools is a third-party library installable via > pip install more_itertools.

참고URL : https://stackoverflow.com/questions/13142347/how-to-remove-leading-and-trailing-zeros-in-a-string-python

반응형