문자열 치환 방법

Leejaegun·2025년 3월 17일

코딩테스트 시리즈

목록 보기
14/49

1. translate()와 maketrans()

1. str.translate()

str.translate()는 문자열에서 특정 문자를 다른 문자로 치환하거나 제거하는 기능을 수행합니다.

기본 문법

str.translate(table)

table: 변환 규칙을 담고 있는 매핑 객체 (보통 str.maketrans()를 이용해 생성)

2. str.maketrans()

tr.maketrans() str.translate()에서 사용할 변환 테이블을 생성하는 함수입니다.

문법

str.maketrans(x[, y[, z]])

x: 변환할 원래 문자들 (문자열)
y: x에서 정의한 문자들이 변환될 문자들 (문자열)
z: 삭제할 문자들 (문자열)
3. translate() + maketrans() 사용 예제

(1) 문자 치환 예제

table = str.maketrans("abc", "123")  # 'a' → '1', 'b' → '2', 'c' → '3'
text = "abc xyz"
translated = text.translate(table)
print(translated)  # "123 xyz"

'a' → '1', 'b' → '2', 'c' → '3'로 변환

(2) 문자 삭제 예제

table = str.maketrans("", "", " ,:")  # " ", ",", ":" 삭제
text = "A man, a plan, a canal: Panama"
cleaned = text.translate(table)
print(cleaned)  # "AmanaplanacanalPanama"

' ,:'에 해당하는 문자를 삭제

(3) 문자 치환 + 삭제 예제

table = str.maketrans("aeiou", "12345", " ,:")  
text = "A man, a plan, a canal: Panama"
translated = text.translate(table)
print(translated)  # "A m1n1pl1n1c1n1lP1n1m1"

'a' → '1', 'e' → '2', 'i' → '3', 'o' → '4', 'u' → '5'
,, : 삭제

replace()

1. str.replace()란?

str.replace()는 문자열에서 특정 부분 문자열을 찾아 다른 문자열로 바꾸는 함수입니다.

기본 문법

str.replace(old, new[, count])

old: 변경할 문자열 (기존 문자열)
new: 대체할 문자열
count (선택): 변경할 횟수 (기본값은 전체)

2. replace() 사용 예제

(1) 단순 문자열 치환

text = "hello world"
new_text = text.replace("hello", "hi")
print(new_text)  # "hi world"

"hello"를 "hi"로 변경
(2) 여러 개의 동일한 문자열 치환

text = "apple banana apple orange apple"
new_text = text.replace("apple", "grape")
print(new_text)  # "grape banana grape orange grape"

"apple"을 "grape"로 모두 변경
(3) 특정 횟수만 치환

text = "apple banana apple orange apple"
new_text = text.replace("apple", "grape", 2)
print(new_text)  # "grape banana grape orange apple"

"apple"을 "grape"로 2번만 변경 (세 번째 "apple"은 그대로 유지)

3. re

re.sub는 Python의 re 모듈에서 제공하는 함수로, 정규 표현식을 사용하여 문자열에서 특정 패턴을 찾아 다른 문자열로 대체하는 기능을 합니다.

📌 기본 문법

import re

re.sub(pattern, repl, string, count=0, flags=0)

✅ 매개변수 설명
pattern: 정규 표현식 패턴 (찾을 문자열 패턴)
repl: 대체할 문자열 또는 함수
string: 원본 문자열
count (기본값: 0): 변경할 횟수 (0이면 모든 패턴 변경)
flags (기본값: 0): 정규식 플래그 (re.IGNORECASE, re.MULTILINE 등)
🔹 기본 사용 예제

import re

text = "Hello World! Hello Python!"
result = re.sub(r'Hello', 'Hi', text)
print(result)
# 출력: "Hi World! Hi Python!"

→ "Hello"를 "Hi"로 변경

🔹 정규 표현식 활용


text = "The price is $100."
result = re.sub(r'\$\d+', '[PRICE]', text)
print(result)

출력: "The price is [PRICE]."
→ $로 시작하는 숫자를 [PRICE]로 변경

🔹 count 사용 (변경 횟수 제한)

text = "apple, apple, banana, apple"
result = re.sub(r'apple', 'orange', text, count=2)
print(result)
# 출력: "orange, orange, banana, apple"

→ 앞에서 2개만 변경

🔹 repl에 함수 사용
대체 문자열 대신 함수를 사용하면, 매칭된 패턴을 동적으로 변경 가능

def replace_func(match):
    return match.group().upper()  # 대문자로 변경

text = "hello world! hello python!"
result = re.sub(r'hello', replace_func, text)
print(result)
# 출력: "HELLO world! HELLO python!"

→ "hello"를 "HELLO"로 변경

🔹 그룹 활용

text = "My number is 123-4567-890."
result = re.sub(r'(\d{3})-(\d{4})-(\d{3})', r'(\1) \2-\3', text)
print(result)
# 출력: "My number is (123) 4567-890."

→ 숫자 그룹을 "(123) 4567-890" 형태로 변환

🔹 플래그 활용 (re.IGNORECASE)

text = "Python is great. python is fun!"
result = re.sub(r'python', 'JavaScript', text, flags=re.IGNORECASE)
print(result)
# 출력: "JavaScript is great. JavaScript is fun!"

→ 대소문자 구분 없이 Python을 JavaScript로 변경

좋은 질문이야! \d\d+는 정규표현식(regular expression)에서 숫자를 의미하지만, 매칭 범위의 차이가 있어:

\d

  • 숫자 한 자리 (0~9) 하나만 매칭
  • 예: "a1b2"\d"1""2" 각각 따로 매칭

\d+

  • 숫자가 하나 이상 연속된 덩어리를 매칭
  • 예: "a123b45"\d+"123""45"덩어리로 매칭

🔍 re.sub("\d", repl, text) vs re.sub("\d+", repl, text) 차이

import re
text = "abc123def456"

re.sub("\d", "X", text)
# 결과: 'abcXXXdefXXX'  ← 숫자 하나하나를 X로 바꿈

re.sub("\d+", "X", text)
# 결과: 'abcXdefX'      ← 연속된 숫자 덩어리 하나를 X로 바꿈

요약

패턴의미예시 텍스트매칭 결과
\d숫자 1자리a12b31, 2, 3
\d+숫자 1자리 이상 (덩어리)a12b312, 3
profile
Lee_AA

0개의 댓글