What is producing “TypeError character mapping must return integer…” in this python code?

后端 未结 1 1966
栀梦
栀梦 2021-01-01 12:38

please, can someone help me with the code bellow? When I run it the logs said:

return method(*args, **kwargs)
  File \"C:\\Users\\CG\\Documents\\udacity\\ro         


        
相关标签:
1条回答
  • 2021-01-01 13:44

    It's probably because the text is being entered as unicode:

    >>> def rot13(st):
    ...     import string
    ...     tab1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ...     tab2 = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM'
    ...     tab = string.maketrans(tab1, tab2)
    ...     return st.translate(tab)
    ... 
    >>> rot13('test')
    'grfg'
    >>> rot13(u'test')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 6, in rot13
    TypeError: character mapping must return integer, None or unicode
    >>> 
    

    This question covers what you need:

    • How do I get str.translate to work with Unicode strings?

    If you are sure that unicode strings aren't important I guess you could just:

    return str(st).translate(tab)
    
    0 讨论(0)
提交回复
热议问题