1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How to Send Unicode DegreeC as a unicode value in a dictionary entry

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I have a python program [pylarexx] (which I did not write) that reads temperature sensors and publishes two MQTT topic messages [..../config and ..../state ] to a Broker running with Home Assistant [HA] (on a RPi) to display the temperature values. Pylarexx works (running under Python 3 on a Raspberry Pi)

    I am trying to use a RPi Pico W to replicate this action, copying the appropriate code into MicroPython. My program works except that the unit_of_measurement °C is not accepted/displayed by HA and is not sent in the same manner as pylarexx. I believe I have copied the code correctly including passing the full "payload" (topic value) through json.dumps() before publishing.

    Using mosquitto_sub I can see the difference in the messages between pylarexx and the Pico W

    pylarexx produces the dictionary value "unit_of_measurement": "\u00b0C"
    The Pico produces "unit_of_measurement": "\\u00b0C" which (understandably) is taken literally by Home Assistant not displayed as °C

    Hacking my attempts, I can get the following (and more diverse representations), none of which works with HA
    "unit_of_measurement": "\\u00b0C"
    "unit_of_measurement": "°C"
    "unit_of_measurement": "u00b0C"

    Having spent many hours on this I was hoping someone had an insight into why I cannot get
    "unit_of_measurement": "\u00b0C" in the MQTT stream.

    I shall go back to studying my reproducion of the pylarexx code to see where I have made the error..

    Test code shows the problem [Python 3]

    degreeC_symbol = r'\u00b0C'
    print(degreeC_symbol, "#this is what I want to send")
    payload = {'unit_of_measurement': degreeC_symbol}
    print(payload, "#How do I stop the '\\' being escaped?")


    Output is

    \u00b0C #this is what I want to send
    {'unit_of_measurement': '\\u00b0C'} #How do I stop the '\' being escaped?

    Continue reading...

Compartilhe esta Página