Swap the first character of a string with the last python character

Asked

Viewed 7,094 times

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.

4 answers

7


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

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

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

def troca(s):
    return s[-1] + s[1:-1] + s[0] if len(s) > 1 else s
  • 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 variable letra1, and not all letters equal, since I was providing a position.

  • Is that the position you are providing -1 is being used exclusively in s, to indicate its last letter - yes being used in replace. In other words, s[-1] ==> "r" happens first, and s.replace("r", letra1) happens second.

0

-4

There is another way too, suddenly can help you but the difference and he writes backwards 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.

-5

A more simplified solution:

Function namePropriation(name){ Return name.substring(0, 1). toUpperCase() + name.substring(1). toLowerCase() }

  • 3

    Douglas, you see the question is about Python? The code you posted is in another language.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.