Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need an explanation

startmsg = "hello"
endmsg = ""
for i in range(0,len(startmsg)):
    endmsg=startmsg[i] + endmsg
print(endmsg)

Why is the result: "olleh", a not "hello"?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As this code iterates, it adds each letter to the front of what’s been iterated over previously. The end result is a reversed string.

As we iterate:

endmsg = "h"

endmsg = "eh"

endmsg = "leh"

endmsg = "lleh"

endmsg = "olleh"

Iterating over indexes like this is not particularly idiomatic Python. Rather, if the index is not needed, it would be more Pythonic to iterate over the characters directly.

startmsg = "hello"
endmsg = ""

for ch in startmsg:
    endmsg = ch + endmsg

print(endmsg)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading