파이썬 문자열 maketrans() 메서드
예시
매핑 테이블을 만들고 translate()
"S" 문자를 "P" 문자로 바꾸는 메서드에서 사용합니다.
txt = "Hello Sam!"
mytable = txt.maketrans("S", "P")
print(txt.translate(mytable))
정의 및 사용
메서드는 지정된 문자를 대체하는 메서드 와 maketrans()
함께 사용할 수 있는 매핑 테이블을 반환합니다 .
translate()
통사론
string.maketrans(x, y, z)
매개변수 값
Parameter | Description |
---|---|
x | Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace. |
y | Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string. |
z | Optional. A string describing which characters to remove from the original string. |
더 많은 예
예시
매핑 테이블을 사용하여 많은 문자를 교체합니다.
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))
예시
maketrans()
메서드 자체는 유니코드로 각 교체를 설명하는 사전을 반환합니다 .
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
print(txt.maketrans(x, y, z))