Remove percent symbol from data received from scrape sensor

I am using the scrape sensor to get values.

One of these values is a percentage

I am struggling to work out how to use the value_template option to remove the percent symbol from the end of the number. There is no white space between the number and the percent symbol.

Is anyone able to help me with this?

Thanks.

Try

value_template: "{{ value.replace('%', '') }}"

Thank you that did the trick. I did try that but thinking back another typo in the config tricked me into thinking that did not work.

There are lots of string manipulation functions that you can use. If the ‘%’ is always the last character, you could also do this to remove one character from the right side of the string:

value_template: "{{ value[:-1] }}"

Of course, the accepted solution works perfectly well, and would only remove ‘%’ characters. Just trying to give more options.

In the future, you may wish to consider using the regex_findall_index filter. It can be used to extract precisely what you want from a string.

Templating - Regular Expressions

Here’s an example containing several numbers. We wish to extract only the numbers ending with %. The numbers can be with or without a decimal separator (period).

{% set value = "The 4th attempt made on 2019-04-02 produced the following result 89.75% which is higher than the previous values of 78.55%, 65.0%, and 50% concentration." %}

This will find all four matching numbers (89.75, 78.55, 65.0, and 50) and report the first one.

{{ value | regex_findall_index('(\d+\.?\d+)%') }}

The four matching numbers are indexed from 0 to 3 so if I want the third one (index=2) I would use this:

{{ value | regex_findall_index('(\d+\.?\d+)%', index=2) }}

The tricky part is learning how to use regular expressions (regex). It’s a powerful string-matching language that can be challenging to master. This interactive regex tester helps one to learn the syntax: regex101

I’ll explain the expression I used so you can see how powerful regex can be:

  • Everything between ( ) is a capture group, meaning that’s what will be extracted and reported. You can have several capture groups within an expression.

  • ( )% means whatever is found in the capture group must be immediately followed by a literal per cent character.

  • \d means to match a number.

  • \d+ means to match one or more numbers.

  • \. means match a period.

  • \.? means optionally match a period.

Here is how it looks in the Template Editor:
Screenshot%20from%202019-04-02%2009-18-49

4 Likes