Add an 'and' before last word from a state

I have a sensor (sensor.bin_next_collection) whose state is either one of the following two set of words:

Refuse, Garden, Food
or
Recycling, Food

I would like to include it in a sentence and make it more grammatically correct by creating a new template sensor that incorporates ‘and’ before the last word, and to remove the comma if only two words.

Refuse, Garden, and Food
or
Recycling and Food

I’ve found various ways to split the text up on these forums, but no easy way to insert an ‘and’ before the last word that can dynamically cater for an entity with either two or three words.

A very basic go at this is as follows:

{% set sensor = states('sensor.bin_next_collection') %}
{% set x = sensor.split(', ')[0] %}
{% set y = sensor.split(', ')[1] %}
{% set z = sensor.split(', ')[2] %}
{{ x + ', ' + y +', and ' + z }}

Result:
Refuse, Garden, and Food

I guess I need to somehow count how many words are in the state and then split / join them up depending on the result.

The two-word template would be something like this:

{% set sensor = "Recycling, Food" %}
{% set x = sensor.split(', ')[0] %}
{% set y = sensor.split(', ')[1] %}
{{ x + ' and ' + y }}

Result:
Recycling and Food

Thanks in advance!

Could you split at the comma then add each split item to an array, then get the length of the array, then do some math to determine which position to place the “comma and” ?

I explained how to do that in the following post:

Fantastic, thank you very much Taras!!

1 Like