Parse strings

I have an mqtt payload that delivers this string,

 "ON 100"

I would like to be able to extract the 100 (or whatever number is delivered) in a data_template and use it as the value for brightness_pct. I have looked at the JINJA documentation but don’t see any string functions that I believe will let you extract portions. Or at least none that I recognize.

Is this possible? Any examples or pointers are appreciated.

Thank you.

What other formats of payload could there be from this topic? You’ll have to consider all of them that could potentially be published. If this is the only one, you could do something like this:

  {%- set value = "ON 100" -%}
  {%- set parts = value.split(" ") -%}
  key = '{{ parts[0] }}', value = '{{ parts[1] }}'

Output

key = 'ON', value = '100'

Much of the time you can also use the methods on python strings as well.

Thanks for the reply. The payload can change, but will always follow that format. Can I do something like this?

  {%- set value = trigger.payload -%}

Thanks again!

Yeah, or just use trigger.payload directly, i.e.:

{{ trigger.payload.split(" ")[0] }}

I just used variables for clarity.

So the value in trigger.payload would be replaced with just “100” in my example?

My advice is to play around with the template dev tool. Just put things in there and see what happens. It’s the best way to learn.

Very good! I appreciate your help. Thanks.