How to replace the last (and only last) character in a string?

kyosohma at gmail.com kyosohma at gmail.com
Thu May 3 10:37:32 EDT 2007


On May 3, 9:27 am, Johny <pyt... at hope.cz> wrote:
> Let's suppose
> s='12345 4343 454'
> How can I replace the last '4' character?
> I tried
> string.replace(s,s[len(s)-1],'r')
> where 'r' should replace  the last '4'.
> But it doesn't work.
> Can anyone explain why?
>
> Thanks
> L.

I think the reason it's not working is because you're doing it kind of
backwards. For one thing, the "string" module is deprecated. I would
do it like this:

s = s.replace(s[len(s)-1], 'r')

Although that is kind of hard to read. But it works.

Mike




More information about the Python-list mailing list