user12495012
user12495012

Reputation:

'string index out of range' when replacing first and last characaters of string?

I am trying to exchange the first and last characters of a string but 'string index out of range' error is occurring. Please help

def front_back(str):
        ind=len(str)-1
        newstring=str.replace(str[0],str[ind])
        newerstring=newstring.replace(newstring[ind],str[0])
        return newerstring

Upvotes: 0

Views: 472

Answers (1)

Vicrobot
Vicrobot

Reputation: 3988

String objects are immutable, means it accepts no change in its elements. The .replace() method is just returning a new instance of string.

You can try this way:

def front_back(s):
    return s[-1] + s[1:-1] + s[0] if len(s) >= 2 else s

print(front_back('hi there'))  #output:  ei therh

Upvotes: 2

Related Questions