Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

알파벳 이외의 모든 문자를 제거하기 위해 Python에서 목록 이해 및 ord()

<시간/>

이 기사에서는 Python 3.x에서 목록 이해와 ord() 함수의 개념을 사용하여 알파벳 이외의 모든 문자를 제거할 수 있는 프로그램에 대해 배웁니다. 또는 그 이전.

알고리즘

1.We Traverse the given string to check the charater.
2.Selection of characters is done which lie in the range of either [a-z] or [A-Z].
3.Using the join function we print all the characters which pass the test together.

예시

def remchar(input):

# checking uppercase and lowercase characters
final = [ch for ch in input if
(ord(ch) in range(ord('a'),ord('z')+1,1)) or (ord(ch) in
range(ord('A'),ord('Z')+1,1))]

return ''.join(final)

# Driver program
if __name__ == "__main__":
   input = "Tutorials@point786._/?"
   print (remchar(input))

출력

Tutorialspoint

ord() 함수는 문자를 인수로 받아들이고 해당 ASCII 값을 반환합니다. 이를 통해 쉽고 빠르게 비교할 수 있습니다.

여기서 우리는 또한 목록의 필요한 모든 요소를 ​​필터링하고 원하는 결과를 얻기 위해 조인 기능의 도움으로 이들을 함께 묶을 수 있는 목록 이해를 구현했습니다.

결론

이 기사에서는 Python에서 List comprehension과 ord() 함수를 사용하여 알파벳 이외의 모든 문자를 제거하는 방법을 배웠습니다.