YouTip LogoYouTip

Python3 String Maketrans

# Python3.x Python3 maketrans() Method [![Image 3: Python3 Strings](#) Python3 Strings](#) * * * ## Description The `maketrans()` method is used to create a translation table for character mapping. For the simplest call with two arguments, the first argument is a string representing the characters to be replaced, and the second argument is also a string representing the target characters. The two strings must be of the same length, establishing a one-to-one correspondence. **Note:** Python 3.4 has removed `string.maketrans()`, replacing it with built-in functions: `bytearray.maketrans()`, `bytes.maketrans()`, and `str.maketrans()`. ## Syntax The syntax for the `maketrans()` method is: string.maketrans(x[, y[, z]]) ## Parameters * x -- Required, a string containing the characters to be replaced. * y -- Optional, a string containing the corresponding mapping characters. * z -- Optional, a string containing the characters to be deleted. ## Return Value Returns a new string after translation. ## Example The following example demonstrates using the `maketrans()` method to convert all vowels to specified numbers: ## Example #!/usr/bin/python3 # Replace the letter 'R' with 'N' txt ="!" mytable = txt.maketrans("R","N") print(txt.translate(mytable)) # Use strings to set the characters to be replaced, one-to-one correspondence intab ="aeiou" outtab ="12345" trantab =str.maketrans(intab, outtab) str="this is string example....wow!!!" print(str.translate(trantab)) The output of the above example is: Nunoob! th3s 3s str3ng 2x1mpl2....w4w!!! Setting the parameter for characters to delete: ## Example #!/usr/bin/python3 txt ="Google Taobao!" x ="mSa" y ="eJo" z ="odnght"# Set the characters to delete mytable = txt.maketrans(x, y, z) print(txt.translate(mytable)) The output of the above example is: Gle Rub Tobo! * * Python3 Strings](#)
← Python3 String RfindGit Fetch β†’