Change the first character of a string by the last character in python

4

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 to my function troca to string 'bar' . The result that I expect the function to return is 'rab' (that is, the first letter changed by the last one), but when I run the code, I have 'bab' as its return. In the python tutor, I see that the code runs normally up to the second replace . in the first replace , my string is 'rar' (so far so good, I changed the first letter of the string to the last one), but in the second, my string simply gets 'bab' , that is, it changes the first one and the last letter, all for the first. Why does it happen? Thank you.

    
asked by anonymous 31.03.2015 / 22:14

3 answers

4

The string.replace method replaces all with occurrences of a substring, not just one. So if your string is rar and you ask to replace r with b , all r s will be replaced, and the result will be bab .

Note that even if only a single instance were replaced, you did not specify which one ... so that the first r in rar would be the first option to be considered, making its string return to bar - for example, if you make "rar".replace("r", "b", 1) .

If you want to replace a specific occurrence in the string, access it by index instead of by content. There are few options for this, so I would use the slice operator along with a concatenation:

def troca(s):
    return s[-1] + s[1:-1] + s[0] if len(s) > 1 else s
    
31.03.2015 / 22:25
0

How about using string slicing to solve your problem:

>>> str = "aeiou"
>>> str[-1:] + str[1:-1] + str[:1]
'ueioa'

Reference: link

    
30.07.2016 / 01:17
-2

There is another way too, of course it can help you but the difference and he writes back and forth the word.

>>> def troca(s):
    return s[::-1]

>>> troca("bar")
'rab'
>>> troca("arara")  #Famosa palavra Palíndrome
'arara'
>>> troca("python")
'nohtyp'

I hope it helps you and other visions.

    
03.04.2015 / 06:09