0

Python Expressions

s = "bananab" while s[0] == s[-1]: mid = len(s)//2 s = s[1:mid] + s[0] + s[mid:-1] print (s) WHY is output "bnaa" instead of "anbana"? I tried to print (s[1:mid]) , (s[0]) and (s[mid:-1]) seperately and it supports my theory that anbana should be the output. Thank you for your time.

14th Feb 2020, 2:54 PM
Toh De Kai
Toh De Kai - avatar
2 Answers
+ 3
If your condition is s[0] == s[-1] then it will continue for (Capitals are used to show equality) BananaB --> condition met AnbanA --> condition met NbaaN --> condition met Bnaa --> Here the loop will break as s[0] != [-1] so it is the output!
14th Feb 2020, 4:45 PM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 2
I'll keep this really short. Just add a print(s) statement inside the while loop and you'll know.
14th Feb 2020, 2:59 PM
XXX
XXX - avatar