Skip to content

Python 문자열 치환: str.replace() 완전 가이드와 그 이상

Updated on

문자열 치환은 텍스트 처리에서 가장 빈번한 작업 중 하나입니다. 사용자 입력을 정리하고, 데이터 형식을 정규화하고, 민감한 정보를 가리고, 템플릿 문자열을 변환해야 합니다. Python의 str.replace()는 간단한 경우를 한 줄로 처리하지만, 대소문자를 무시하는 매칭, 정규식 패턴 또는 조건부 치환이 필요할 때는 부족합니다. 잘못된 도구를 선택하면 간단한 작업을 불필요하게 복잡하게 만들거나 복잡한 작업에 취약한 코드를 작성하게 됩니다.

이 가이드는 Python에서의 문자열 치환에 대한 모든 접근 방식을 다룹니다 -- 기본적인 str.replace()부터 정규식 기반 re.sub(), 문자 수준 translate(), 그리고 실제 텍스트 처리를 위한 실용적인 패턴까지.

📚

str.replace(old, new, count)

가장 간단하고 일반적인 메서드입니다. old의 모든 발생을 new로 치환합니다. 선택적 count로 치환 횟수를 제한할 수 있습니다.

text = "Hello World, Hello Python, Hello Everyone"
 
# 모든 발생 치환
print(text.replace("Hello", "Hi"))
# Hi World, Hi Python, Hi Everyone
 
# 처음 2개만 치환
print(text.replace("Hello", "Hi", 2))
# Hi World, Hi Python, Hello Everyone
 
# 부분 문자열 제거 (빈 문자열로 치환)
messy = "  extra   spaces   here  "
print(messy.replace(" ", ""))
# extraspaceshere

주요 동작

  • 새 문자열을 반환합니다 (Python에서 문자열은 불변입니다)
  • 기본적으로 대소문자를 구분합니다
  • count가 지정되지 않으면 모든 발생을 치환합니다
  • old를 찾지 못하면 원래 문자열을 그대로 반환합니다
original = "Python is great"
new = original.replace("great", "awesome")
print(original)  # Python is great (변경 없음)
print(new)       # Python is awesome

대소문자 무시 치환

str.replace()는 항상 대소문자를 구분합니다. 대소문자를 무시하는 치환에는 re.sub()re.IGNORECASE 플래그를 사용합니다.

import re
 
text = "Python is Great, python is Fun, PYTHON is Everywhere"
 
# 대소문자 무시 치환
result = re.sub(r'python', 'Java', text, flags=re.IGNORECASE)
print(result)
# Java is Great, Java is Fun, Java is Everywhere

re.sub()를 사용한 정규식 치환

re.sub(pattern, replacement, string, count, flags)는 정규식 패턴의 일치를 치환합니다.

import re
 
# 숫자를 '#'으로 치환
text = "Call 555-1234 or 555-5678"
print(re.sub(r'\d', '#', text))
# Call ###-#### or ###-####
 
# 전체 전화번호 치환
print(re.sub(r'\d{3}-\d{4}', '[삭제됨]', text))
# Call [삭제됨] or [삭제됨]
 
# 여러 공백을 하나의 공백으로 치환
messy = "too    many     spaces   here"
print(re.sub(r'\s+', ' ', messy))
# too many spaces here

캡처 그룹 사용

import re
 
# 성과 이름 바꾸기
names = "Smith, John\nDoe, Jane\nBrown, Bob"
swapped = re.sub(r'(\w+), (\w+)', r'\2 \1', names)
print(swapped)
# John Smith
# Jane Doe
# Bob Brown
 
# 날짜에 형식 추가
dates = "Meeting on 2026-02-10 and 2026-03-15"
formatted = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', dates)
print(formatted)
# Meeting on 02/10/2026 and 03/15/2026

동적 치환을 위한 함수 사용

조건부 치환에는 문자열 대신 함수를 전달합니다:

import re
 
def censor_word(match):
    word = match.group()
    return word[0] + '*' * (len(word) - 1)
 
text = "The password is secret and the code is hidden"
censored = re.sub(r'secret|hidden', censor_word, text)
print(censored)
# The password is s***** and the code is h*****
import re
 
# 특정 단어만 제목 대문자로 변환
def smart_capitalize(match):
    word = match.group()
    minor_words = {'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to'}
    if word.lower() in minor_words:
        return word.lower()
    return word.capitalize()
 
title = "the quick BROWN fox AND the lazy DOG"
result = re.sub(r'\b\w+\b', smart_capitalize, title)
print(result)
# the Quick Brown Fox and the Lazy Dog

다중 치환

replace() 호출 연쇄

text = "Hello World! How are you?"
result = text.replace("Hello", "Hi").replace("World", "Earth").replace("you", "they")
print(result)  # Hi Earth! How are they?

딕셔너리 기반 치환

많은 치환에는 딕셔너리와 re.sub()를 사용합니다:

import re
 
def multi_replace(text, replacements):
    """딕셔너리를 사용하여 여러 부분 문자열을 치환합니다."""
    pattern = re.compile('|'.join(re.escape(k) for k in replacements))
    return pattern.sub(lambda m: replacements[m.group()], text)
 
text = "The cat sat on the mat with another cat"
replacements = {
    'cat': 'dog',
    'mat': 'rug',
    'sat': 'stood',
}
 
print(multi_replace(text, replacements))
# The dog stood on the rug with another dog

translate()를 사용한 문자 수준 치환

개별 문자를 치환하려면 str.translate()str.maketrans()가 가장 빠른 옵션입니다:

# 문자 치환: a->@, e->3, o->0
table = str.maketrans('aeo', '@30')
text = "Hello World"
print(text.translate(table))
# H3ll0 W0rld
 
# 특정 문자 제거
remove_vowels = str.maketrans('', '', 'aeiouAEIOU')
print("Hello World".translate(remove_vowels))
# Hll Wrld
 
# 한 번의 호출로 치환과 제거
table = str.maketrans({'a': '@', 'e': '3', ' ': None})
print("apple pie".translate(table))
# @ppl3pi3

메서드 비교

메서드최적 용도정규식속도유연성
str.replace()간단한 리터럴 치환없음가장 빠름낮음
re.sub()패턴 매칭, 복잡한 규칙있음보통가장 높음
str.translate()단일 문자 매핑없음매우 빠름낮음
연쇄 .replace()소수의 리터럴 치환없음빠름낮음
Dict + re.sub()많은 동시 치환있음보통높음

실용적인 예제

텍스트 정리 및 정규화

import re
 
def clean_text(text):
    """처리를 위해 텍스트를 정규화합니다."""
    text = text.strip()
    text = re.sub(r'\s+', ' ', text)           # 공백 축소
    text = re.sub(r'[^\w\s.,!?-]', '', text)   # 특수 문자 제거
    text = text.lower()
    return text
 
raw = "  Hello!!!   This is    MESSY @#$ text...  "
print(clean_text(raw))
# hello!!! this is messy text...

템플릿 문자열 치환

template = "Dear {name}, your order #{order_id} ships on {date}."
 
data = {
    'name': 'Alice',
    'order_id': '12345',
    'date': 'Feb 15, 2026',
}
 
# str.format_map 사용 (수동 치환보다 우수)
result = template.format_map(data)
print(result)
# Dear Alice, your order #12345 ships on Feb 15, 2026.

민감한 데이터 가리기

import re
 
def redact_pii(text):
    """이메일, 전화번호, SSN을 가립니다."""
    text = re.sub(r'\b[\w.]+@[\w.]+\.\w+\b', '[이메일]', text)
    text = re.sub(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[전화번호]', text)
    text = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN]', text)
    return text
 
msg = "Contact john@example.com or call 555-123-4567. SSN: 123-45-6789"
print(redact_pii(msg))
# Contact [이메일] or call [전화번호]. SSN: [SSN]

Jupyter에서의 텍스트 데이터 처리

텍스트 정리와 변환은 반복적인 작업입니다 -- 샘플 데이터에 대해 패턴을 테스트하고, 정규식을 조정하고, 결과를 검증합니다. RunCell (opens in a new tab)은 Jupyter용 AI 에이전트로, 텍스트 처리 파이프라인을 인터랙티브하게 구축하고 디버그하며, 실제 데이터에 대해 치환 패턴을 실시간으로 테스트할 수 있습니다.

FAQ

Python에서 부분 문자열을 치환하려면?

간단한 치환에는 str.replace(old, new)를 사용합니다: "hello world".replace("world", "python")"hello python"을 반환합니다. 이것은 모든 발생을 치환합니다. 세 번째 인수를 추가하여 치환 횟수를 제한할 수 있습니다: text.replace("a", "b", 2)는 처음 2개의 일치만 치환합니다.

Python에서 대소문자 무시 치환을 하려면?

re.sub()re.IGNORECASE 플래그를 사용합니다: re.sub(r'python', 'Java', text, flags=re.IGNORECASE). 내장 str.replace() 메서드는 대소문자 무시 매칭을 지원하지 않습니다.

여러 다른 문자열을 한 번에 치환하려면?

치환 딕셔너리에서 정규식 패턴을 구축합니다: 모든 키와 일치하는 컴파일된 패턴을 만들고, 람다를 사용하여 각 일치에 대한 치환을 조회합니다. 또는 소수의 리터럴 치환에는 .replace() 호출을 연쇄합니다.

str.replace()와 re.sub()의 차이점은?

str.replace()는 리터럴 문자열 매칭만 수행합니다 -- 더 빠르고 간단합니다. re.sub()는 정규식을 사용하여 패턴 매칭, 캡처 그룹, 역참조, 함수 기반 치환을 지원합니다. 간단한 리터럴 교체에는 str.replace()를, 패턴 유연성이 필요할 때는 re.sub()를 사용하세요.

Python에서 문자열에서 문자를 제거하려면?

세 가지 접근 방식: str.replace(char, "")는 특정 부분 문자열의 모든 발생을 제거합니다. str.translate(str.maketrans("", "", chars))는 지정된 문자를 효율적으로 모두 제거합니다. re.sub(r"[pattern]", "", text)는 정규식 패턴과 일치하는 문자를 제거합니다.

결론

Python은 문자열 치환을 위한 여러 도구를 제공하며, 각각 다른 복잡도 수준에 적합합니다. 간단한 리터럴 교체에는 str.replace()를, 패턴 매칭과 복잡한 규칙에는 re.sub()를, 빠른 문자 수준 매핑에는 str.translate()를 사용하세요. 여러 동시 치환에는 딕셔너리 기반 re.sub() 접근 방식이 코드를 깔끔하고 유지보수하기 쉽게 유지합니다.

📚