본문 바로가기

개인 공부

8/1 월_re 모듈, translate 메서드, 정규표현, range, 코딩 테스트 연습(Python)

728x90

1. re.sub()

re 모듈의 re.sub(pattern, repl, string, count) 메서드는 원래 문자열에서 정규식 pattern을 repl값으로 대체한 후 새 문자열을 반환한다. count는 문자열에서 pattern을 대체하려는 횟수를 의미한다.

문자를 제거하고 교체할 필요가 없기 때문에 repl은 빈 문자열과 같다. 아래 코드 예제는 re.sub() 메서드를 사용하여 Python에서 문자열의 문자를 대체하는 방법을 보여준다.

import re

string = "Hey! What's up?"
string = re.sub("\!|\'|\?","",string)
print(string) # Hey Whats up

출처: https://www.delftstack.com/ko/howto/python/remove-certain-characters-from-string-python/

 

2. .translate()

여러 개의 문자열을 한 번에 치환하거나 삭제할 수 있으므로 편리하다. translate 메서드는 str.maketrans 함수와 함께 사용한다.

text ="translate、allows・us・to・delete・multiple・letters。"
table = text.maketrans({
    '、': ' ', #왼쪽은 치환하고 싶은 문자, 오른쪽은 새로운 문자
    '。': '.',
    '・': ' ',
})
print(text.translate(table)) # translate allows us to delete multiple letters.

출처: https://engineer-mole.tistory.com/238 [매일 꾸준히, 더 깊이:티스토리]

 

3. 정규표현

r"[a-z]"는 소문자의 알파벳 모두를 의미하는 정규표현이다. 「r」은 raw string으로 정규표현 시에 입력을 추천한다.

r"[1-9]"는 정수 모두를 의미한다.

 

4. range(start, end, -1)

range 범위 내에 높은 수, 낮은 수, -1 옵션을 주면 내림차순이 된다. -1씩 감소!

728x90