파이썬 문자열 translate() 메서드
예시
"S" 문자를 "P" 문자로 바꿉니다.
#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict
= {83: 80}
txt = "Hello Sam!"
print(txt.translate(mydict))
정의 및 사용
이 translate()
메서드는 지정된 일부 문자가 사전이나 매핑 테이블에 설명된 문자로 대체되는 문자열을 반환합니다.
메서드를 사용
maketrans()
하여 매핑 테이블을 생성합니다.
사전/표에 문자가 지정되지 않은 경우 해당 문자는 대체되지 않습니다.
사전을 사용하는 경우 문자 대신 ASCII 코드를 사용해야 합니다.
통사론
string.translate(table)
매개변수 값
Parameter | Description |
---|---|
table | Required. Either a dictionary, or a mapping table describing how to perform the replace |
더 많은 예
예시
매핑 테이블을 사용하여 "S"를 "P"로 바꿉니다.
txt = "Hello Sam!"
mytable = txt.maketrans("S", "P")
print(txt.translate(mytable))
예시
매핑 테이블을 사용하여 많은 문자를 교체합니다.
txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = txt.maketrans(x,
y)
print(txt.translate(mytable))
예시
매핑 테이블의 세 번째 매개변수는 문자열에서 제거하려는 문자를 설명합니다.
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = txt.maketrans(x, y, z)
print(txt.translate(mytable))
예시
위와 같은 예이지만 매핑 테이블 대신 사전을 사용합니다.
txt = "Good night Sam!"
mydict = {109: 101, 83: 74, 97: 111, 111: None,
100: None, 110: None, 103: None, 104: None, 116: None}
print(txt.translate(mydict))