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

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!

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:

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

return str(st).translate(tab)

Need Your Help

Registered models do not show up in admin

django django-admin

I added a model to admin via admin.site.register, and it does not show up in admin. Since admin is so "It just works", I have no idea of how to debug this. Pointers?

Android Database Transaction

android sqlite transactions

I have created a database. I want to do the Transaction. SaveCustomer() contains more than one statement to insert records into Customer, CustomerControl, Profile, Payment table at that time.