Home > Enterprise >  Python How to compare and replace last character of a string
Python How to compare and replace last character of a string

Time:02-16

I can't find a solution to this on the internet. I imagine it's quite easy to do but I'm not very experienced with Python.

I have this code:

if word[-1] == "i":
    return s[:-1]   "y"
    
else:
    return s

I need to check the last character and only if the condition is true I then change it. How do I do that? The compiler gives me a SyntaxError

CodePudding user response:

The SyntaxError might be happening because you're using return outside of a function definition. If you're not in a function, then avoid using return and use a variable instead, as shown in @ksohan answer:

if word[-1] == "i":
    word = word[:-1]   "y"
# `else` is not really necessary now
    

CodePudding user response:

You can use slice to remove the last character and then add the new character

word = "hi"
if word[-1] == "i":
    word = word[:-1]   'y'

print(word)

And if you want to write a function use something like the following:

def changeLastChar(word, remove, add):
    if word[-1] == remove:
        word = word[:-1]   add
    return word


print(changeLastChar('hiii', 'i', 'y'))
  • Related