본문 바로가기
IT/Python Basic

[Python] 특집 개념 - translate 함수

by Echinacea 2025. 2. 24.
반응형

 

 

🚀 1. translate 함수란?

translate() 함수문자열 내 특정 문자들을 다른 문자로 치환하거나 제거할 때 사용하는 함수예요.

 

💡 쉽게 이해하기

  • 🔤 특정 문자들을 한 번에 바꿀 수 있어요! (예: a → 1, b → 2)
  • ❌ 특정 문자들을 쉽게 제거할 수 있어요! (예: 공백, 특수 문자 제거)
  • 🏎 반복문을 쓰는 것보다 빠르고 효율적이에요.

 

📌 활용 예시

  • 텍스트 정제 (불필요한 문자 제거)
  • 특정 문자 변환 (예: 암호화, 치환)
  • 유효한 문자만 남기기 (예: 숫자만 남기기)

즉, translate()는 문자열을 효율적으로 변환하는 데 매우 유용한 함수예요!


 

 

🚀 2. translate() 함수의 기본 사용법

 

📌 문법

str.translate(table)
  • table: 문자 변환을 위한 매핑 테이블 (str.maketrans()로 생성)

 

📌 기본 예제 (문자 변환)

text = "hello world"
trans_table = str.maketrans("aeiou", "12345")
print(text.translate(trans_table))  # 출력: h2ll4 w4rld

문자 a, e, i, o, u가 각각 1, 2, 3, 4, 5로 변경되었어요!

 

📌 문자 제거하기

text = "hello, world!"
trans_table = str.maketrans("", "", "!,")  # `!,` 제거
print(text.translate(trans_table))  # 출력: hello world

특수 문자 !와 ,가 제거되었어요!


 

 

🚀 3. str.maketrans()와 함께 사용하기

translate() 함수는 단독으로 사용할 수 없고, 변환 테이블을 str.maketrans()를 통해 생성해야 해요.

 

📌 str.maketrans() 기본 문법

str.maketrans(from_str, to_str, delete_chars)
  • from_str: 변환할 문자들
  • to_str: 변경할 문자들 (길이가 from_str과 같아야 함)
  • delete_chars: 삭제할 문자들 (옵션)

 

📌 예제: 다중 문자 변환과 제거

text = "hello world!123"
trans_table = str.maketrans("aeiou", "12345", "!1")
print(text.translate(trans_table))  # 출력: h2ll4 w4rld23

a, e, i, o, u는 1, 2, 3, 4, 5로 변환되고, !와 1은 삭제되었어요!


 

 

🚀 4. translate()와 replace() 차이점

 

기능 translate() replace()

여러 문자 치환 ✅ 가능 ❌ 하나씩만 가능
특정 문자 제거 ✅ 가능 ❌ 직접적인 제거 불가능
성능 🚀 빠름 (C언어 기반) ⏳ 상대적으로 느림

 

📌 비교 예제

# translate 사용
text = "hello world"
trans_table = str.maketrans("ho", "HO")
print(text.translate(trans_table))  # 출력: HellO wOrld

# replace 사용
text = text.replace("h", "H").replace("o", "O")
print(text)  # 출력: HellO wOrld

translate()는 한 번에 변환할 수 있지만, replace()는 여러 번 호출해야 해요!


 

 

🚀 5. 실전 활용 예제

 

 

✅ 1) 알파벳을 암호화하기

text = "hello world"
trans_table = str.maketrans("abcdefghijklmnopqrstuvwxyz",
                            "zyxwvutsrqponmlkjihgfedcba")
print(text.translate(trans_table))  # 출력: svool dliow

알파벳을 반대로 치환하는 간단한 암호화 방식!

 

 

✅ 2) 숫자와 특수문자 제거

text = "Hello123! How are you?"
trans_table = str.maketrans("", "", "0123456789!?")
print(text.translate(trans_table))  # 출력: Hello How are you

숫자와 !?가 삭제되어 깔끔한 문장이 되었어요.

 

 

✅ 3) 한글 자음과 모음 제거

text = "안녕하세요! 반갑습니다."
trans_table = str.maketrans("ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ", "", "!.")
print(text.translate(trans_table))  # 출력: 안녀하세요 반갑습니다

특정 자음이나 특수문자를 제거할 때도 활용 가능!


 

 

✅ 마무리 정리

  • translate()는 문자열 변환 및 제거를 위한 강력한 함수예요.
  • str.maketrans()와 함께 사용해야 하고, 한 번에 여러 문자 변환 가능해요.
  • 특정 문자 삭제, 텍스트 정제, 간단한 암호화 등에 활용할 수 있어요.
  • replace()보다 성능이 뛰어나므로, 다중 문자 변환이 필요할 때 translate()를 사용하세요!

 

반응형

댓글