Jin Jin - 2 months ago 9
Python Question

Python: For loop not working properly

Why is the for loop not working properly? It's just returned only one element.

1.

rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
for i in a:
l = re.sub(" ","/",i)
r = l.split("/")
r.reverse()
rx = " ".join(r)
return rx
a=string_m(rx)
print(a)


Outputs:

abc


2.

rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
for i in a:
l = re.sub(" ","/",i)
r = l.split("/")
r.reverse()
rx = " ".join(r)
return rx
a=string_m(rx)
print(a)


Outputs:

i hg


-- Can someone help me to see what I am doing wrong?

Answer
import re

rx = ['abc', 'de fg', 'hg i']

def string_m(a=rx):
    new = []
    for i in a:
        l = re.sub(" ","/",i)
        r = l.split("/")
        #r.reverse()
        rx = " ".join(r)
        new.append(rx)
    new.reverse()
    return new

a=string_m(rx)
print(a)

Your biggest problem is that you return the result of the first iteration of your for loop instead of after the for loop has finished.

Another issue is that strings cannot be reversed with the reverse() method. If you want to reverse the output, Try the above.

Comments