Skip to content
Advertisement

Python For Loop Count and Insert Numbers beside words

I have a problem regarding Python, I want to count the list item and then put a number beside the value of text.

This is the output I want:

test = 1
me = 2
texting = 3

This is the output I always get:

test = 3
me = 3
texting = 3

Here is my line of code:

text =  request.form['title']
text2 = text.splitlines()
count = len(text2)
textarray = []
x = 0;
while(x <count):
    for txt in text2:
        textarray = [txt + " = " + str(x) for txt in text2]
    x = x+1
string = '<br>'.join(textarray)
return render_template('index.html', text=string)

Advertisement

Answer

Fix

You don’t need 2 loops, just iterate over text2 and increment your xn then append to the array, don’t recreate it wit nonsense

textarray = []
x = 1
for txt in text2:
    textarray.append(txt + " = " + str(x))
    x = x + 1

Improve

Use enumerate to generate increasing value along with an iterable

textarray = []
for idx, txt in enumerate(text2, 1):
    textarray.append(f"{txt} = {idx}")

Best

Use generator construction and inline it

text = "testnmentexting"

result = '</br>'.join(
    (f"{word}={idx}" for idx, word in enumerate(text.splitlines(), 1))
)

# return render_template('index.html', text=result)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement