Python’s string translate method; Through this tutorial, i am going to show you what is the python string translate method and how to use it.
Python String translate() Method
The python string translate() method returns a string where each character is mapped to its corresponding character in the translation table.
The syntax of the translate() method is:
string.translate(table)
Parameters of Python String translate()
The translate() method takes a single parameter:
- table – a translation table containing the mapping between two characters; usually created by maketrans()
The return value from Python String translate()
The translate() method returns a string where each character is mapped to its corresponding character as per the translation table.
Example 1: Translation/Mapping using translation table with translate()
# first string firstString = "abc" secondString = "def" thirdString = "ghi" string = "xyz" print("Original string:", string) translation = string.maketrans(firstString, secondString, thirdString) # translate string print("Translated string:", string.translate(translation))
Output
Original string: abcdef Translated string: idef
Example 2: Python string.translate remove characters
Python string translate() function with ord() function replace each character in the string using the given translation table.
Let’s check the example below:
s = 'abc abc abc' print(s.translate({ord('a'): None}))
Output
bc bc bc
Example 3: Removing Spaces from a String Using translate() and replace()
string = ' P Y T H O N' print(string.replace(' ', '')) # PYTHON print(string.translate({ord(i): None for i in ' '})) # PYTHON
Output
PYTHON PYTHON
Example 4: Python remove newline from string using translate
s = 'ab\ncd\nef' print(s.replace('\n', '')) print(s.translate({ord('\n'): None}))
Output
abcdef abcdef
Be First to Comment