웹사이트 검색

Python을 사용하여 문자열로 제공된 숫자에서 선행 0을 제거합니다.


이 기사에서는 문자열로 주어진 숫자에서 선행 0을 제거하는 Python 프로그램을 배웁니다.

문자열 형식의 숫자를 사용한다고 가정합니다. 이제 아래 제공된 방법을 사용하여 모든 선행 0(숫자 시작 부분에 있는 0)을 제거하겠습니다.

사용된 방법

다음은 이 작업을 수행하는 데 사용되는 다양한 방법입니다.

  • For 루프 및 제거() 함수 사용

  • 정규식 사용

  • int() 함수 사용

방법 1: For 루프 및 제거() 함수 사용

알고리즘(단계)

다음은 원하는 작업을 수행하기 위해 따라야 할 알고리즘/단계입니다. -

  • 함수에 문자열로 전달된 숫자에서 선행 0을 제거하는 deleteLeadingZeros() 함수를 만듭니다.

  • len() 함수를 사용하여 문자열 길이를 탐색하려면 for 루프를 사용하세요.

  • len() 함수 − 객체의 항목 수는 len() 메소드에 의해 반환됩니다. len() 함수는 객체가 문자열일 때 문자열의 문자 수를 반환합니다.

  • != 연산자와 함께 if 조건문을 사용하여 문자열의 현재 문자가 0이 아닌지 확인하세요.

  • 슬라이싱을 사용하여 선행 0 뒤에 있는 문자열의 나머지 문자를 가져옵니다.

  • 입력 문자열에서 선행 0을 모두 제거한 후 결과 문자열을 반환합니다.

  • 앞에 오는 0이 없으면 0을 반환합니다.

  • 문자열로 전달된 입력 숫자를 저장할 변수를 만듭니다.

  • 선행 0을 제거한 후 결과 문자열을 얻기 위해 입력 문자열을 전달하여 위에 정의된 deleteLeadingZeros() 함수를 호출합니다.

  • 같은 방법으로 앞에 0이 없는 다른 문자열도 확인합니다.

예

다음 프로그램은 for 루프 및 제거() 함수를 사용하여 문자열로 전달된 숫자에서 모든 선행 0을 제거하는 문자열로 반환합니다.

# creating a function that removes the leading zeros
# from a number passed as a string to the function
def deleteLeadingZeros(inputString):
   # traversing through the length of the string
   for k in range(len(inputString)):
      # checking whether the current character of a string is not 0
      if inputString[k] != '0':
         # getting the remaining string using slicing
         outputString= inputString[k::]
         # returning resultant string after removing leading 0s
         return outputString
   # returning 0 if there are no leading 0s found in the entire string
   return "0"
# input number as a string
inputString = "0002056"
print("Given String is:", inputString)
# calling the deleteLeadingZeros() function by passing the input string to it
print("After Removing Leading Zeros:", deleteLeadingZeros(inputString))
# checking it for other strings having no leading 0s
inputString = "256"
print("Given String is:", inputString)
# calling the deleteLeadingZeros() function by passing the input string to it
print("After Removing Leading Zeros:", deleteLeadingZeros(inputString))

산출

실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.

Given String is: 0002056
After Removing Leading Zeros: 2056
Given String is: 256
After Removing Leading Zeros: 256

방법 2: 정규식 사용

알고리즘(단계)

다음은 원하는 작업을 수행하기 위해 따라야 할 알고리즘/단계입니다. -

  • regex(re) 모듈을 가져오려면 import 키워드를 사용하십시오.

  • 함수에 문자열로 전달된 숫자에서 선행 0을 제거하는 deleteLeadingZeros() 함수를 만듭니다.

  • 입력 문자열에서 선행 0을 제거하기 위한 정규식 패턴을 저장할 변수를 만듭니다.

  • sub() 함수를 사용하여 일치하는 정규식 패턴을 빈 문자열로 바꿉니다.

  • sub() 함수(주어진 패턴과 일치하는 모든 항목이 대체 문자열로 대체되는 문자열을 반환합니다).

  • 입력 문자열에서 선행 0을 모두 제거한 후 결과 문자열을 인쇄합니다.

예

다음 프로그램은 정규 표현식을 사용하여 문자열로 전달된 숫자에서 모든 선행 0을 제거하는 문자열로 반환합니다.

# importing re module
import re
# creating a function that removes the leading zeros
# from a number passed as a string to the function
def deleteLeadingZeros(inputString):
   # regex pattern for removing leading zeros from an input string
   regexPattern = "^0+(?!$)"
   # Replace the matched regex pattern with an empty string
   outputString = re.sub(regexPattern, "", inputString)
   # returning output string after removing leading 0s
   return outputString
# input number as a string
inputString = "0002056"
print("Given String is:", inputString)
# calling the deleteLeadingZeros() function by passing the input string to it
print("After Removing Leading Zeros:", deleteLeadingZeros(inputString))

산출

실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.

Given String is: 0002056
After Removing Leading Zeros: 2056

방법 3: int() 함수 사용

알고리즘(단계)

다음은 원하는 작업을 수행하기 위해 따라야 할 알고리즘/단계입니다. -

  • 함수에 문자열로 전달된 숫자에서 선행 0을 제거하는 deleteLeadingZeros() 함수를 만듭니다.

  • int() 함수(주어진 객체에서 정수를 반환)를 사용하여 입력 문자열을 정수로 변환합니다. 이 함수는 앞에 오는 0을 모두 제거합니다.

  • 입력 문자열에서 선행 0을 모두 제거한 후 결과 숫자를 반환합니다.

예

다음 프로그램은 int() 함수를 사용하여 문자열로 전달된 숫자에서 선행 0을 모두 제거하는 숫자로 반환됩니다.

# creating a function that removes the leading zeros
# from a number passed as a string to the function
def deleteLeadingZeros(inputString):
   # converting the input string to an integer removes all the leading zeros
   result = int(inputString)
   # returning the resultant number after removing leading zeros
   return result
# input number as a string
inputString = "0002056"
print("Given String is:", inputString)
# calling the deleteLeadingZeros() function by passing the input string to it
print("After Removing Leading Zeros:", deleteLeadingZeros(inputString))

산출

실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.

Given String is: 0002056
After Removing Leading Zeros: 2056

결론

이 기사에서는 세 가지 다른 방법을 사용하여 문자열로 제공된 숫자에서 선행 0을 제거하는 방법을 배웠습니다. 문자열, 목록 또는 튜플과 같은 반복 가능 항목의 하위 집합을 얻기 위해 슬라이싱을 사용하는 방법을 배웠습니다. 또한 정규식 모듈을 활용하여 한 패턴을 다른 패턴으로 바꾸는 방법도 배웠습니다.

관련기사: