[SOLVED] UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0'


I’m having a problem trying to program a python script. I have openhab 2.5 with openhabian and using the Rule Engine.

I have an item from my tado binding linked to a zone thing (https://www.openhab.org/addons/bindings/tado/). This item is of type Number and dimension Temperature. When using the paper UI it shows its value as 20.0 ºC.

Now, I’m trying to make an example rule to alert me the value. My code is:

from core.actions import NotificationAction

item = itemRegistry.getItem("CalefacciN_TargetTemperature")
msg = u"Salón programado a " + str(item.getState())

The problem is that whenever I run this rule I get the error:

2020-01-02 16:47:15.510 [ERROR] [internal.handler.ScriptActionHandler] - Script execution failed: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 5: ordinal not in range(128) in <script> at line number 4

I think it’s related with the º character.

I have tried different ways to fix it, but I can’t find the correct way to get the value of the item.

Any help? Thanks.


msg = u"Salón programado a {}".format(item.getState())

I gotta say that dealing with unicode in Python is not something I’m expert at but I believe this will force the item state to unicode whereas calling str does not.

1 Like

Thank you @rlkoshak,

That works perfect!!!

To use a specific encoding (e.g. ‘utf-8’) use the encoding argument for pandas to csv:

df.to_csv(file_name, sep='\t', encoding='utf-8')