Value template - cut special characters from sensor string? - Solved

I’ve got a scrape sensor that grabs a tag made up of a number and degree symbol. If it passes “299 and the degree symbol”, I want to take the 299 and use Float to convert it. I can’t seem to find a way to slice the string using the value template to get rid of the degree symbol. Slice and Truncate don’t work and Trim is only for whitespace. Replace would if it were a regular character not an ASCII symbol (using a Linux system).

My next step is to write an Appdaemon app to slice it, but I’d like to keep it simple if I’ve overlooked something.

EDIT:
Replace() will work with special characters if they are entered correctly (I was using ASCII keyboard shortcuts). The tip I found was to use the Character Map accessory built into both Ubuntu and Windows to enter the exact character. It’s searchable so Ctrl-F “degree” found the degree symbol. My value template looks like this:

{{states(“sensor.ferry_course”)|replace(“”,"")|replace(“°”,"")|float|round(0)}}

2 Likes

Thanks, @blackshoals for the solution.

I experienced same problem accessing the TP-Link HS-110 state attributes. I am using the HS-110 to manage the 120V charging system for my Nissan Leaf so I know when the car is actually charging. However, the state attributes are returned to HA as strings apparently so using just the ‘float’ parameter doesn’t work.

For example, the following template statement run in the developer tools:

{{ states.switch.leaf_charger.attributes}}

returns the following attribute data:

{‘current_consumption’: ‘0.8 W’, ‘total_consumption’: ‘204.97 kW’, ‘voltage’: ‘122.72 V’, ‘current’: ‘0.0 A’, ‘daily_consumption’: ‘2.71 kW’, ‘friendly_name’: ‘Leaf Charger’}

Encoding the template statement as a float:

{{ states.switch.leaf_charger.attributes.voltage|float }}

returns a value of 0.0, not 122.72.

The following statement uses ‘replace’ to remove the ‘V’ and converts the result to a float works, resulting in the value of 122.72:

{{ states.switch.leaf_charger.attributes.voltage|replace(‘V’,‘’)|float }}

1 Like

The JSON response I get from a query is:
{“bus”: “344”, “time”: “2”, “distance”: “625”, “estate”: “0”}
All data is treated as text. How could I convert them to an “int” type?
The following instruction does not work (| int):
'{{states.sensor.origendatosautobuses.attributes.time | int}} ’

It is still a text type data

Thank you!

Is that an actual response or something you’ve typed yourself? Some of the quotation marks are typographic, try replacing them with straight ASCII ones " ". If you do that, type casting should work fine (at least it does so for me).

This was very heplful in replacing decimal separators to commas in sensor values.

|replace('.', ',')

2 Likes