Is there a way in yaml to extract e.g. the left three characters from a string, similar to this?
LEFT("Friday", 3) = "Fri"
Is there a way in yaml to extract e.g. the left three characters from a string, similar to this?
LEFT("Friday", 3) = "Fri"
Put this into Home Assistant’s Template Editor and experiment with it.
{% set x = "Friday" %}
{{ x[:3] }}
Result is: Fri
Example here:
Here’s a more complicated example:
{% set num = "8886758934" %}
{{ "("+num[:3]+") "+num[3:-4]+"-"+num[-4:] }}
Result is: (888) 675-8934
Here’s an explanation of “slice notation”:
Brilliant, thanks!
If I have a value template with joined strings, how to limit the join?
{% if is_state(“media_player.sonos_wohnzimmer”,“playing”) %}({{state_attr(“media_player.sonos_wohnzimmer”, “media_channel”)}} - {{state_attr(“media_player.sonos_wohnzimmer”, “media_artist”)}} - {{state_attr(“media_player.sonos_wohnzimmer”, “media_title”)}})[:3]{% else %}gestoppt{% endif %}
brings as result e.g.
(foo - bar - lore)[:3]
and not as wanted
foo
You have to use “[:3]” with a string. You just inserted it as a literal. Try this:
{% if is_state("media_player.sonos_wohnzimmer","playing") %}
{{(state_attr("media_player.sonos_wohnzimmer", "media_channel") or "" + " - " + state_attr("media_player.sonos_wohnzimmer", "media_artist") or "" + " - " + state_attr("media_player.sonos_wohnzimmer", "media_title") or "")[:3]}}
{% else %}gestoppt{% endif %}
Thanks. Will try that. Wanted to avoid a two-liner like
{% if is_state(“media_player.sonos_wohnzimmer”,“playing”) %}{% set sonos_wohnzimmer_history = state_attr(“media_player.sonos_wohnzimmer”, “media_channel”)+" - “+state_attr(“media_player.sonos_wohnzimmer”, “media_artist”)+” - "+state_attr(“media_player.sonos_wohnzimmer”, “media_title”) %}{{sonos_wohnzimmer_history[:250]}}{% else %}gestoppt{% endif %}
what is of course working.
{% if is_state('media_player.sonos_wohnzimmer', 'playing') %}
{{ ('{} - {} - {}'.format(state_attr('media_player.sonos_wohnzimmer', 'media_channel'), state_attr('media_player.sonos_wohnzimmer', 'media_artist'), state_attr('media_player.sonos_wohnzimmer', 'media_title')))[:250] }}
{% else %} gestoppt {% endif %}
Thanks for this way as well. Need to get used to all this options.
I have following string “abcxyzwww”
I need to extract only "yzw"
[:3] only print first 3 character but if I need to extract data range like 3-5 chracter then how can do it?
Thanks
{%- set string = "abcxyzwww" %}
{{ string[4:7] }}
I recommend putting this into the Template tab in Developer Tools and playing around with the numbers on either side of the colon. It was how I got a workable understanding of how slice notation works (although the linked explanation earlier in the thread is also helpful).