Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Translate Python String ตาม Dictionary ที่กำหนด

ใช้ translate() ร่วมกับ maketrans() จากโมดูล string

ตัวอย่าง

from string import maketrans

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "This is a string example....wow!!!"
print(str.translate(trantab))

ผลลัพธ์

Th3s 3s 1 str3ng 2x1mpl2....w4w!!!

ตัวอักษร a→1, e→2, i→3, o→4, u→5