Sensor Template If State_Attr Contains '-'

In my configuration.yaml I have an entry for a sensor template where I’m bringing in a weather value from the REST platform. It is working fine until the external system doesn’t send a numerical value but a string of dashes and not always the same number of dashes. “- - -”
I’d like to test if the value has a dash and if so substitute a null or empty or blank value. Maybe something like this but I’m unsure how to do it. Any ideas?

{%- if is_state_attr('sensor.station_data','windAvg10') | contains('-') %}

Here’s the yaml entry.

  - platform: template
    sensors:
        wind_avg_10m_davis:
            friendly_name: Davis Wind Avg 10m
            value_template: "{{ state_attr('sensor.station_data','windAvg10') }}"
            unit_of_measurement: "mph"
            device_class: wind_speed

Something to play with in Dev Tools/Templates.

1 Like

Another approach:


value_template: |-
  {% set w = 'sensor.station_data'' %}
  {{ state_attr(w,'windAvg10') if state_attr(w,'windAvg10') is number else '?' }}

Returns an empty string if the value of windAvg10 is non-numeric.

- platform: template
    sensors:
      wind_avg_10m_davis:
        friendly_name: Davis Wind Avg 10m
        value_template: "{{ state_attr('sensor.station_data','windAvg10') | float('') }}"
        unit_of_measurement: "mph"
        device_class: wind_speed
1 Like
value_template: "{{ state_attr('sensor.station_data','windAvg10') | replace('-', '') }}"
1 Like

Do I read that as: If state_attr is not a float value then substitue an empty string for its value.

If windAvg10 contains a value that thefloat filter cannot convert to a floating point number (in other words, the value is a non-numeric string) then float will report the default value I specified which is an empty string (but you can change it to whatever you want).

So if the value of windAvg10 doesn’t contain any numeric characters (merely one or more hyphens), float will report an empty string.

1 Like