Python string maketrans














































Python string maketrans



Python String : maketrans()


This article demonstrates how to use of maketrans() method in string.

The string maketrans() method returns a mapping table for translation usable for translate() method.

In simple terms, the maketrans() method is a static method that creates a one to one mapping of a character to its translation/replacement.It creates a Unicode representation of each character for translation.

This translation mapping is then used for replacing a character to its mapped character when used in translate() method.


Syntax :

string.maketrans(x,y,z)


Parameter Values :

ParameterDescription
xIf only one argument is supplied, it must be a dictionary.
The dictionary should contain 1-to-1 mapping from a single character string to its translation OR a unicode number (97 for 'a') to its translation.

yoptional. If two arguments are passed, it must be two strings with equal length.
Each character in the first string is a replacement to its corresponding index in the second string.
zOptional. If three arguments are passed, each character in the third argument is mapped to None.


Returns :

The maketrans() method returns a translation table with a 1-to-1 mapping of a Unicode ordinal to its translation/replacement.



Sample Code :

1.

Translation table using a dictionary with maketrans()

# example dictionary
dict = {"a""123""b""456""c""789"}
string = "abc"
print(string.maketrans(dict))

# example dictionary
dict = {97"123"98"456"99"789"}
string = "abc"
print(string.maketrans(dict))
Output :
{97: '123', 98: '456', 99: '789'}
{97: '123', 98: '456', 99: '789'}

Here, a dictionary dict is defined. It contains a mapping of characters a,b and c to 123, 456 and 789 respectively.

maketrans() creates a mapping of the character's Unicode ordinal to its corresponding translation.

So, 97 ('a') is mapped to '123', 98 'b' to 456 and 99 'c' to 789. This can be demonstrated from the output of both dictionaries.



2.

Translation table using two strings with maketrans()

# first string
firstString = "abc"
secondString = "def"
string = "abc"
print(string.maketrans(firstString, secondString))

# example dictionary
firstString = "abc"
secondString = "defghi"
string = "abc"
print(string.maketrans(firstString, secondString))
Output :
{97: 100, 98: 101, 99: 102} 
Traceback (most recent call last):                                                                                                            
  File "main.py", line 11in <module>                                                                                                        
    print(string.maketrans(firstString, secondString))                                                                                        
ValueError: the first two maketrans arguments must have equal length


Here first, two strings of equal length "abc" and "def" are defined. And the corresponding translation is created.

Printing only the first translation gives you a 1-to-1 mapping to each character's Unicode ordinal in firstString to the same indexed character on the secondString.

In this case, 97 ('a') is mapped to 100 ('d'), 98 ('b') to 101 ('e') and 99 ('c') to 102 ('f').

Trying to create a translation table for unequal length strings raises a ValueError exception indicating that the strings must have equal length.



3.

Translational table with removable string with maketrans()

# first string
firstString = "abc"
secondString = "def"
thirdString = "abd"
string = "abc"
print(string.maketrans(firstString, secondString, thirdString))
Output :
{97: None, 98: None, 99: 102, 100: None}

Here, first the mapping between the two strings firstString and secondString are created.

Then, the third argument thirdString resets the mapping of each character in it to None and also creates new mapping for non-existent characters.

In this case, thirdString resets the mapping of 97 ('a') and 98 ('b') to None, and also creates a new mapping for 100 ('d') mapped to None.




Hence,we can see above function maketrans() returns a translation table to be used in translate function.



**********END OF ARTICLE **********


More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 115 0
Python string swapcase 93 0
Python string title 97 0
Python string startswith 103 0
Python string replace 144 0
Python string translate 85 0
Python string rpartition 86 0
Python string partition 74 0
Python string splitlines 114 0
Python string rsplit 80 0
Python string split 76 0
Python string rindex 82 0
Python string rfind 107 0
Python string upper 80 0
Python string lower 82 0
Python string maketrans 91 0
Python string strip 81 0
Python string rstrip 92 0
Python string lstrip 80 0
Python string rjust 97 0
Python string ljust 96 0
Python string len 82 0
Python string join 76 0
Python string casefold 83 0
Python string isprintable 85 0
Python string encode 79 0
Python string isdecimal 85 0
Python string isidentifier 78 0
Python string isupper 78 0
Python string istitle 80 0
Python string isspace 100 0
Python string isnumeric 102 0
Python string isdigit 83 0
Python string islower 85 0
Python string isalpha 96 0
Python string isalnum 102 0
Python string index 88 0
Python string find 94 0
Python string expandtabs() 81 0
Python string endswith 92 0
Python string count 86 0
Python string capitalize 78 0
Python string center 85 0
Python string Introduction 99 0
Python string Template 141 0
Python string Formatter 145 0
Python string printable 199 0
Python string whitespace 146 0
Python string punctuation 104 0
Python string octdigits 87 0
Python string hexdigits 104 0
Python string digits 80 0
Python string ascii_letters 344 0
Python string ascii_lowercase 147 0
Python string ascii_uppercase 157 0
How to Create Download Manager in Python 524 0
Python random weibullvariate 165 0
python random paretovariate 135 0
Python random vonmisesvariate 178 0
Python random normalvariate 196 0
Python random lognormvariate 120 0
Python random gauss 120 0
Python random gammavariate 131 0
Python random expovariate 194 0
Python random betavariate 186 0
Python random triangular 117 0
Python random uniform 141 0
Python random random 117 0
Python random sample 183 0
Python random shuffle 179 0
Python random choices 234 0
Python random choice 166 0
Python random randint 149 0
Python random randrange 214 0
Python random getrandbits 141 0
Python random setstate 137 0
Python random getstate 178 0
Python random seed 168 1
Python random Introduction 175 0

Comments