주어진 숫자 앞의 모든 숫자를 제거하는 Python 프로그램
이 글에서는 파이썬에서 주어진 숫자 앞의 모든 숫자를 제거하는 방법을 배웁니다.
사용된 방법
다음은 이 작업을 수행하는 다양한 방법입니다.
List Comprehension, Split(), enumerate() 및 index() 함수 사용
re 모듈 사용
슬라이싱, index() 및 replacement() 함수 사용
예
입력 문자열과 입력 숫자를 취했다고 가정합니다. 이제 입력 문자열에서 입력 숫자 앞의 모든 숫자를 제거하겠습니다.
입력
inputString = 'hello 6 8 10 tutorialspoint 15 python codes'
inputNumber = 10
산출
Resultant string after removing digits before input number{ 10 }:
hello 10 tutorialspoint 15 python codes
위의 입력 문자열에서 입력 숫자 10 앞의 숫자는 6, 8이므로 입력 문자열에서 제거되고 결과 문자열이 유지됩니다.
방법 1: List Comprehension, Split(), enumerate() 및 index() 함수 사용
enumerate() 메소드는 iterable에 카운터를 추가하고 enumerate 객체를 반환합니다.
통사론
enumerate(iterable, start=0)
매개변수
반복 가능 − 반복을 지원하는 모든 시퀀스/객체/반복 가능일 수 있습니다.
start − enumerate()는 이 값부터 계산을 시작합니다. start를 지정하지 않으면 값 0이 사용됩니다.
index() 함수 − 제공된 값이 처음 나타나는 위치는 index() 함수에 의해 반환됩니다.
join()은 문자열 구분 기호로 구분된 시퀀스의 요소를 결합하는 데 사용되는 Python의 문자열 함수입니다. 이 함수는 시퀀스 요소를 연결하여 문자열로 변환합니다.
알고리즘(단계)
다음은 원하는 작업을 수행하기 위해 따라야 할 알고리즘/단계입니다.
입력 문자열을 저장할 변수를 만듭니다.
입력 목록을 인쇄합니다.
-
입력 숫자를 저장할 다른 변수를 만듭니다.
split() 함수를 사용하여 문자열을 단어 목록으로 분할하고 index() 함수를 사용하여 문자열에 있는 입력 숫자의 인덱스를 가져옵니다.
enumerate() 함수를 사용하여 인덱스와 요소가 있는 입력 문자열을 반복하고 주어진 숫자 앞의 모든 숫자/숫자를 제거합니다.
목록을 문자열로 변환하려면 join() 함수를 사용하세요.
입력된 숫자 앞의 숫자를 제거한 후 결과 문자열을 인쇄합니다.
예
다음 프로그램은 list Comprehension, Split(), enumerate() 및 index() 함수를 사용하여 입력 문자열에서 주어진 숫자 앞의 모든 숫자를 제거합니다.
# input string
inputString = 'hello 6 8 10 tutorialspoint 15 python codes'
# printing input string
print("Input String:", inputString)
# input number
inputNumber = 10
# splitting a string into a list of words and
# getting the index of input number in a string
num_index = inputString.split().index(str(inputNumber))
# Getting the result using list comprehension
resultantList = [element for p, element in enumerate( inputString.split()) if not (p < num_index and element.isdigit())]
# converting the list into a string using join() function
resultantStr = ' '.join(resultantList)
# printing resultant string after removing digits before input number
print("Resultant string after removing digits before input number{", inputNumber, "}:\n", resultantStr)
산출
실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.
Input String: hello 6 8 10 tutorialspoint 15 python codes
Resultant string after removing digits before input number{ 10 }:
hello 10 tutorialspoint 15 python codes
방법 2: re 모듈 사용
예
다음 프로그램은 re 모듈을 사용하여 입력 문자열에서 주어진 숫자 앞의 모든 숫자를 제거합니다.
# importing re(regex) module
import re
# input string
inputString = 'hello 6 8 10 tutorialspoint 15 python codes'
# printing input string
print("Input String:", inputString)
# input number
inputNumber = 10
# Using regex substitution
resultantStr = re.sub('[023456789]', '', inputString[0: inputString.index( str(inputNumber))]) + inputString[inputString.index(str(inputNumber)):]
# printing resultant string after removing digits before input number
print("Resultant string after removing digits before input number{", inputNumber, "}:\n", resultantStr)
산출
실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.
Input String: hello 6 8 10 tutorialspoint 15 python codes
Resultant string after removing digits before input number{ 10 }:
hello 10 tutorialspoint 15 python codes
방법 3: 슬라이싱, index() 및 replacement() 함수 사용
replace() 함수 − 이전 하위 문자열의 모든 항목을 다른 새 하위 문자열로 바꾸는 문자열의 복사본을 반환합니다.
통사론
string.replace(old, new, count)
알고리즘(단계)
다음은 원하는 작업을 수행하기 위해 따라야 할 알고리즘/단계입니다.
str() 함수를 사용하여 입력 숫자를 문자열로 변환하고, index() 함수를 사용하여 입력 문자열에서 입력 숫자의 인덱스를 가져옵니다.
모든 숫자를 문자열로 저장하는 변수를 초기화합니다.
입력 숫자 뒤의 문자열 자르기
for 루프를 사용하여 위 숫자의 각 문자를 탐색합니다.
바꾸기() 함수를 사용하여 현재 숫자를 공백/공백으로 바꿉니다.
입력된 숫자 앞의 숫자를 제거한 후 결과 문자열을 인쇄합니다.
예
다음 프로그램은 슬라이싱, index() 및 replacement() 함수를 사용하여 입력 문자열에서 주어진 숫자 앞의 모든 숫자를 제거합니다.
# input string
inputString = 'hello 6 8 10 tutorialspoint 15 python codes'
# printing input string
print("Input String:", inputString)
# input number
inputNumber = 10
# getting the index of input number in a string
num_index = inputString.index(str(inputNumber))
# storing all the digits in a string
digits_str = "0123456789"
# slicing the string till before the input number
first_str = inputString[:num_index]
# slicing the string after input number
secd_str = inputString[num_index:]
# traversing through each character of digits
for c in digits_str:
# replacing the first string with a null character
first_str = first_str.replace(c, "")
# printing resultant string after removing digits before input number
print("Resultant string after removing digits before input number{", inputNumber, "}:\n", (first_str+secd_str))
산출
실행 시 위 프로그램은 다음과 같은 출력을 생성합니다.
Input String: hello 6 8 10 tutorialspoint 15 python codes
Resultant string after removing digits before input number{ 10 }:
hello 10 tutorialspoint 15 python codes
결론
이 기사에서는 주어진 숫자 앞의 모든 숫자를 제거하는 세 가지 방법을 설명했습니다. enumerate() 함수를 사용하여 인덱스와 요소 값을 반복하는 방법도 배웠습니다.