Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is producing "TypeError character mapping must return integer..." in this python code?

Tags:

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\rot13serendipo\main.py", line 51, in post     text = rot13(text)   File "C:\Users\CG\Documents\udacity\rot13serendipo\main.py", line 43, in rot13     return st.translate(tab) TypeError: character mapping must return integer, None or unicode    INFO     2012-04-28 20:02:26,862 dev_appserver.py:2891] "POST / HTTP/1.1" 500 - 

I know the error must be in rot13(). But when I run this procedure in the IDE it works normally.

Here my code:

import webapp2  form= """   <html>   <head>     <title>Unit 2 Rot 13</title>   </head>    <body>     <h2>Enter some text to ROT13:</h2>     <form method="post">       <textarea name="text"                 style="height: 100px; width: 400px;"></textarea>       <br>       <input type="submit">     </form>   </body>    </html> """  def rot13(st):     import string     tab1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'     tab2 = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM'     tab = string.maketrans(tab1, tab2)     return st.translate(tab)  class MainHandler(webapp2.RequestHandler):     def get(self):         self.response.out.write(form)      def post(self):         text = self.request.get("text")         text = rot13(text)         self.response.out.write(text)   app = webapp2.WSGIApplication([('/', MainHandler)],                           debug=True) 

Thanks in advance for any help!

like image 478
craftApprentice Avatar asked Apr 28 '12 20:04

craftApprentice


1 Answers

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) 
like image 115
Andrew Barrett Avatar answered Oct 04 '22 23:10

Andrew Barrett