Reputation: 11
I am trying to split out a shopping list string that looks like the following:
['Milk', 'Bread', 'sugar', 'rinse aid']
The string has 4 shopping list items, whereby I want to remove the [] at the front and the end, remove the '', and separate each item on a separate line if possible.
Upvotes: 1
Views: 4520
Reputation: 1946
First I will presume that what you have is a list of items which you would like to show in a web page-
app.route('/myList')
def myList():
list=['Milk', 'Bread', 'sugar', 'Colagate']
return render_template('shoppingList.html',slist=list)
and in the shoppingList.html
{% for x in slist %}
<div class="someClass">{{ x }}</div>
{% endfor %}
this should work for a list
If you have a string that looks like-
listStr="['Milk', 'Bread', 'sugar', 'Colagate']"
what you can do is define-
def listMaker(lst):
listStr=listStr.replace(']','')
listStr=listStr.replace('[','')
listStr=listStr.replace(',','')
listStr=listStr.replace('\'','')
list=listStr.split(' ')
return list
and then call this function-
app.route('/myList')
def myList():
listStr="['Milk', 'Bread', 'sugar', 'Colagate']"
list=listMaker(listStr)
return render_template('shoppingList.html',slist=list)
the HTML code remains the same.
Upvotes: 1
Reputation: 18763
Your shopping list is not a string
, its a list
.
You can use for loop to iterate through each item and print it separately,
{% set shoppinglist = ['Milk', 'Bread', 'sugar', 'rinse aid'] %}
{%- for item in shoppinglist -%}
{{ item }}
{% endfor %}
Output,
Milk
Bread
sugar
rinse·aid
You can test it here
Upvotes: 1