본문 바로가기
data science/python

dict 을 이용한 일괄 문자열 바꿔치기

by 꼰대코더 2025. 2. 12.

s = "hello world, have a great day"

r_dict = {"hello": "hi", "world": "earth", "great": "wonderful"}

 

1. Loop 를 이용한 replace

for key, value in r_dict.items():
    s = s.replace(key, value)

print(s)
-> "hi earth, have a wonderful day"

 

2. 정규표현 re.sub()

import re

# "스페이스 + ( hello|world|great ) + 스페이스"
# lambda match는 매치 될때마다 매치 문자열 오브젝트가 할당 => 문자열은 object.group()
# s 는 초기 문자열
result = re.sub(r'\b(?:' + '|'.join(r_dict.keys()) + r')\b', lambda match: r_dict[match.group()], s)

print(result)
-> "hi earth, have a wonderful day"