Objective
The last item in a comma-separated list should be prefaced with the word “and” as opposed to a comma.
Example
Convert this:
Front, Garage, Patio, Yard
to this:
Front, Garage, Patio and Yard
Applications
Useful for creating more natural-sounding phrases for speech synthesis. For example:
Front and Garage doors are open.
as opposed to
Front, Garage doors are open.
Method
Paste this into the Template Editor and experiment with it:
{% set doors = 'Front, Garage, Patio, Yard' %}
{{' and '.join(doors.rsplit(', ', 1))}}
Real-World Example
This is used to report any doors left open.
{% set pause = '<silence msec="750"/>' %}
{% set qty = states('sensor.all_doors')|int %}
{% set plural = 's' if qty > 1 else '' %}
{% set prep = 'are' if qty > 1 else 'is' %}
Attention! {{pause}} There {{prep}} {{qty}} door{{plural}} left open.
{{pause}} {{' and '.join(states('sensor.open_doors').rsplit(', ', 1))}} door{{plural}}
{{pause}} {{prep}} open.