5
I have the following function:
def troca(s):
letra1 = s[0]
letra2 = s[-1]
s = s.replace(s[0], letra2)
s = s.replace(s[-1], letra1)
return s
troca ('bar')
As you can see, I provide as an argument for my function troca
the string 'bar'
. The result I hope the function returns is 'rab'
(that is, the first letter exchanged for the last), but when executing the code, I have as return 'bab'
.
In python tutor, I see that the code runs normally until the second replace
. in the first replace
, my string is 'rar'
(so far so good, I changed the first letter of the string for the last), but in the second, my string simply stays 'bab'
, that is, he changes the first and last letter, all for the first. Why does this happen? Thank you.
Strange, I thought I was accessing by the index. For example, on the line
s = s.replace(s[-1], letra1)
, i thought it replaced the last position of the string with the letter I stored in the variableletra1
, and not all letters equal, since I was providing a position.– Jefferson Carvalho
Is that the position you are providing
-1
is being used exclusively ins
, to indicate its last letter - yes being used inreplace
. In other words,s[-1] ==> "r"
happens first, ands.replace("r", letra1)
happens second.– mgibsonbr