I\'m a Python newbie.
How come this doesn\'t work in Python 3.1?
from string import maketrans # Required to call maketrans function.
intab = \"aei
Strings are not bytes.
This is a simple definition in Python 3.
Strings are Unicode (which are not bytes) Unicode strings use "..."
or '...'
Bytes are bytes (which are not strings) Byte strings use b"..."
or b'...'
.
Use b"aeiou"
to create a byte sequence composed of the ASCII codes for certain letters.
maketrans is a string function
use below logic to use translate using maketrans
print('maketrans' , '& translate')
intab = "aeiou"
outtab = "12345"
str = "Fruits are delicious and healthy!!!"
trantab = str.maketrans(intab, outtab)
print (str.translate(trantab))
Here is an example of performing translation and deletion, in Python 2 or 3:
import sys
DELETE_CHARS = '!@#$%^*()+=?\'\"{}[]<>!`:;|\\/-,.'
if sys.version_info < (3,):
import string
def fix_string(s, old=None, new=None):
if old:
table = string.maketrans(old, new)
else:
table = None
return s.translate(table, DELETE_CHARS)
else:
def fix_string(s, old='', new=''):
table = s.maketrans(old, new, DELETE_CHARS)
return s.translate(table)
In Python 3, the string.maketrans()
function is deprecated and is replaced by new static methods, bytes.maketrans()
and bytearray.maketrans()
.
This change solves the confusion around which types were supported by the string module.
Now str
, bytes
, and bytearray
each have their own maketrans
and translate
methods with intermediate translation tables of the appropriate type.