문자열에서 특정 문자를 변경하기 위해 쓰는 정규 표현식 re.sub
- re.sub 사용법
re.sub(pattern,replace,string) pattern: 바꿀문자 replace: 새로 변경할 문자 string: 변경할 문자열(원본 문자열) |
- 사용 예시
import re
re 모듈을 import 한다
1. 반점(,) 제거
import re
s = 'Hello, World'
print("변경 전:", s)
s1_new = re.sub(",","",s)
print("변경 후:", s1_new)
[결과]
2. 반점(,)을 느낌표(!)로 변경
import re
s = 'Hello, World'
print("변경 전:", s)
s1_new = re.sub(",","!",s)
print("변경 후:", s1_new)
[결과]
3. 대소문자 알파벳 제거 예시
import re
s = 'Hello, World'
print("변경 전:", s)
s1_new = re.sub("[A-Za-z]","",s)
print("변경 후(전체):", s1_new)
[결과]
4. 숫자 제거
import re
s = 'Hello, World0123456789'
print("변경 전:", s)
s1_new = re.sub("[0-9]","",s)
print("변경 후:", s1_new)
[결과]
반응형
'Python' 카테고리의 다른 글
[Python] 파이썬 numpy 배열 사용하기(2)/numpy.where (0) | 2021.10.19 |
---|---|
[Python] 파이썬 numpy 배열 사용하기(1) (0) | 2021.10.17 |
라즈베리파이에서 파이썬으로 음악재생 (pygame) (0) | 2021.10.01 |
파이썬 playsound 음악 중지하기 (0) | 2021.10.01 |
Python 특정 문자 제거 및 치환 하기 (0) | 2021.09.29 |
댓글