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

前端 未结 10 2245
生来不讨喜
生来不讨喜 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:07

    If you absolutely insist on working with 8-bit bytes:

    >>> intab = b"aeiou"
    >>> outtab = b"12345"
    >>> trantab = bytes.maketrans(intab, outtab)
    >>> strg = b"this is string example....wow!!!";
    >>> print(strg.translate(trantab));
    b'th3s 3s str3ng 2x1mpl2....w4w!!!'
    >>>
    
    0 讨论(0)
  • 2020-12-18 20:08

    Stop trying to learn Python 3 by reading Python 2 documentation.

    intab = 'aeiou'
    outtab = '12345'
    
    s = 'this is string example....wow!!!'
    
    print(s.translate({ord(x): y for (x, y) in zip(intab, outtab)}))
    
    0 讨论(0)
  • 2020-12-18 20:09

    Here's my final Python (3.1) code posted here just for reference:

    "this is string example....wow!!!".translate(bytes.maketrans(b"aeiou",b"12345"))
    

    Short and sweet, love it.

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

    Hey here is the simple one liner which worked perfectly for me

    import string
    a = "Learning Tranlate() Methods"
    print (a.translate(bytes.maketrans(b"aeiou", b"12345")))*
    
    OUTPUT :::: L21rn3ng Tr1nl1t2() M2th4ds
    0 讨论(0)
  • 2020-12-18 20:12

    You don't need to use bytes.maketrans() when str would be simpler and eliminate the need for the 'b' prefix:

    print("Swap vowels for numbers.".translate(str.maketrans('aeiou', '12345')))
    
    0 讨论(0)
  • 2020-12-18 20:14
    "this is string example....wow!!!".translate(str.maketrans("aeiou","12345"))
    

    This works, and no additional byte transformation. I don't know the reason why to use byte instead of str.

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