How to remove trailing whitespaces from string in Jinja?

Viewed 8161

In my case all the strings are single-worded and the trailing whitespaces from the strings need to be removed, e.g., 'hello '→ 'hello'; 'hello '→ 'hello'.

One approach could be using split, i.e,

{% if ' ' in word %}
  {% set word = word.split(' ')[0] %}
{% endif %}

This works since the strings are one-worded. I am quite sure there must be a better approach.

3 Answers

Silly me! It is .strip(), i.e., 'hello '.strip().

It's not .strip() ... it's | trim . Such as {{ some_variable_string_name | trim }}

you can simply iterate though your list and remove the trailing spaces. by default split() function has whitespaces.

data=['hello ','hello   ',...]
new_data=[]
for i in data:
  new_data.append(i.split())
Related