Reputation: 13
i need to write a function that returns a copy of the string with the rightmost 2 characters moved to the front. Here is my code:
def go_right(mystr):
if mystr >= 2:
for i in range(len(mystr)):
a = mystr[-2:] + mystr[:-2]
return a
The above code works fine, but I can't seem to wrap my head around why I cannot do this:
def go_right(mystr):
if mystr >= 2:
for i in range(len(mystr)-2):
a = mystr[-2:] + mystr
return a
If I used the function above if I passed in hello it would simply return "lohello". Why doesn't the -2 seem to affect mystr? I thought it was supposed to iterate through every character except for the last 2? If anyone could help clarify this for me I'd appreciate it.
Upvotes: 1
Views: 117
Reputation: 11686
You can also greatly simplify your code as:
def go_right(mystr):
return mystr[-2:] + mystr[:-2]
inputs with length 0, 1, or 2 are returned unchanged.
Upvotes: 0
Reputation: 11038
Here you have a logical mistake:
for i in range(len(mystr)):
a = mystr[-2:] + mystr[:-2]
you are assigning the new value to a
for len(mystr)
times.
All you need to actually do is call
return mystr[:-2] + mystr[:-2]
Mind your i
index, you're not using that to access list elements, because you're using the slice notation instead.
See this question for further reference on that.
Upvotes: 0
Reputation: 2795
I am slightly confused as to why you are using a loop for this... the loop isn't really doing anything for you in either case. To answer your question though, it happens because you're adding all of mystr to mystr[-2:]. Which makes sense, as by running through the loop, mystr isn't changed.
Upvotes: 0
Reputation: 21773
In
def go_right(mystr):
if mystr >= 2:
for i in range(len(mystr)):
a = mystr[-2:] + mystr[:-2]
return a
The variable i
is never used and mystr is never modified. So a = mystr[-2:] + mystr[:-2]
is executed len(mystr) times, doing the same thing over and over.
So it is no surprise that changing the length of the for loop does not change anything, since the for loop's existence does not do anything.
Your method is equivalent to
def go_right(mystr):
if mystr >= 2:
a = mystr[-2:] + mystr[:-2]
return a
And there is still an error in this code. Instead of mystr >= 2, you mean len(mystr) >= 2, like so:
def go_right(mystr):
if len(mystr) >= 2:
a = mystr[-2:] + mystr[:-2]
return a
(The semantics of comparing a string and a number is to always compare them false, e.g. "a" >= 2
is True
)
However, now this will give an error when the length of mystr is 0 or 1: 'UnboundLocalError: local variable 'a' referenced before assignment'. One way to solve this is:
def go_right(mystr):
if len(mystr) >= 2:
return mystr[-2:] + mystr[:-2]
return mystr
Upvotes: 2