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

jay graves jaywgraves at gmail.com
Thu May 3 10:49:25 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?

Instead of doing it that way, you should use slicing.

>>> s='12345 4343 454'
>>> s = s[:-1] + 'r'
>>> print s
12345 4343 45r
>>>

See
http://docs.python.org/tut/node5.html#strings

HTH.
Jay Graves





More information about the Python-list mailing list