본문 바로가기
Python

Python 특정문자 치환하기 re.sub 정규표현식

by 고체물리학 2021. 10. 5.

문자열에서 특정 문자를 변경하기 위해 쓰는 정규 표현식 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)

 

[결과]

 

 

 

반응형

댓글