Search code examples
pythonunicodewxpythondecodetextctrl

How do I safely decode a degrees symbol in a wxPython app?


I have a debug app I've been writing which receives data from a C-based process via UDP. One of the strings sent to me contains a ° character - Unicode U+00B0 (which incidentally breaks the StackOverflow search function!). When my wxPython application tries to append that string to a text box I get a UnicodeDecodeError.

My first attempt to fix the issue simply caught that error (because the app apparently does send some bad messages. The problem is that the app also uses the character to report various temperatures around the unit and that's something we really need to log. Changing the source app is out of my control, so how can I detect and decode those symbols into something the wxTextCtrl can display?


Solution

  • pdc got it right, the following works fine (but fails without the decode):

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import wx
    
    app = wx.PySimpleApp()
    app.TopWindow = wx.Frame(None)
    field = wx.TextCtrl(app.TopWindow)
    field.Value += '°'.decode('ISO8859-1')
    app.TopWindow.Show()
    app.MainLoop()