How come string.maketrans does not work in Python 3.1?

前端 未结 10 2253
生来不讨喜
生来不讨喜 2020-12-18 19:49

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         


        
相关标签:
10条回答
  • 2020-12-18 20:17

    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.

    0 讨论(0)
  • 2020-12-18 20:18

    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))
    
    0 讨论(0)
  • 2020-12-18 20:23

    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)
    
    0 讨论(0)
  • 2020-12-18 20:25

    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.

    0 讨论(0)
提交回复
热议问题