Append to string

Hi all
I’m new to programming in HA. I’m playing around in Template Tools and cannot get something to append to a string. Can someone please assist?

{% set val = "" %}
{% set ns = namespace(c = 0) %}
 {% for i in ['1','2','3'] %}
   {% set val = val|string + "5" %}
   {{ val }}
   {% set ns.c = ns.c + 1 %}
 {% endfor %}
val = {{ val }}

This is the output:

5
   
 
   
   5
   
 
   
   5
   
 
val = 

I want it to be:

val = 555

Thank you

If you just remove the last line then the result in a template sensor should be 555.
In the template tools it looks differently, but all spaces are removed in a sensor.

Yeah no reason to bother, but here’s how https://jinja.palletsprojects.com/en/3.0.x/templates/#whitespace-control

{% set val = "" %}
{% set ns = namespace(c = 0) %}
{% for i in ['1','2','3'] -%}
  {{ 'val = ' if loop.first -}}
  {% set val = val|string + "5" -%}
  {{ val -}}
  {% set ns.c = ns.c + 1 -%}
{% endfor %}
1 Like

In Jinja2, the scope of a variable defined within a for-loop is limited to the for-loop. A variable defined outside a for-loop can be modified within a for-loop but that value isn’t preserved outside of the for-loop. To get the variable’s scope to cover inside and outside the for-loop, use namespace.

{% set ns = namespace(c = '') %}
{% for i in range(0,3) %}
 {% set ns.c = ns.c ~ '5' %}
{% endfor %}
{{ ns.c }}

In addition, is you use the + operator it will naturally attempt to compute the sum of numbers. If you want to append numeric strings, and eliminate any ambiguity of whether the values should be summed or concatenated, use the ~ operator.

1 Like

Thank you all for your swift answers :slight_smile:

1 Like

Hi 123 Taras

How can I assign the final ns.c to an input_text.value?

{% set ns = namespace(c = '') %}
{% for i in range(0,3) %}
 {% set ns.c = ns.c ~ '5' %}
{% endfor %}
{% input_text.c =  ns.c %}

does not work - (input_text.c is defined in HA)

service: input_text.set_value
data:
  value: >-
    {% set ns = namespace(c = '') %} {% for i in range(0,3) %}  {% set ns.c =
    ns.c ~ '5' %} {% endfor %} {{ ns.c }}
target:
  entity_id: input_text.c

change that to

{{ ns.c }}
1 Like

Thank you Petro