Home > Back-end >  What is wrong in my code? Swapping first and last letter of a word, using method replace
What is wrong in my code? Swapping first and last letter of a word, using method replace

Time:10-27

Given any word, swap the first and the last letter's position then return the new string. If that is a one-letter word, return the word. I'm aware the fastest way to do this is to use slicing, or join but I want to try a new approach using replace.

def front_back(any_string):
  if len(any_string) <= 1:
    return any_string
  else:
    temp = any_string.replace(any_string[0],list(any_string)[-1])
    final_str = temp.replace(temp[-1],list(any_string)[0])
  print(final_str)
  
front_back('line')

Instead of "einl", it returns "linl".

CodePudding user response:

def front_back(any_string: str) -> str:
    if len(any_string) < 2:
        return any_string
    else:
        return any_string[-1]   any_string[1:-1]   any_string[0]


print(front_back('line'))

CodePudding user response:

def front_back(any_string):
    if len(any_string) <= 1:
        return any_string
    else:
        temp = any_string.replace(any_string[0],list(any_string)[-1]) #1
        final_str = temp.replace(temp[-1],list(any_string)[0]) #2
    print(final_str)

front_back('line')
#Instead of "einl", it returns "linl"
it is because 
any_string="Line"
#1 when you replace "L"(any_string(0)) with "e"(any_string(-1))
then the value becomes "eine" and it stores in temp.

#2. you are trying to replace the last "e" which is placed at any_string(-1)
here what happens is you have two "e" characters in "eine" that is in temp 
variable.
when you try to replace "L" in place of "e". it replaces both "e" characters.
the starting "e" character and ending "e" character.making it "linl"   
  • Related