How to replace the last (and only last) character in a string?
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Thu May 3 10:45:54 EDT 2007
In <1178202464.201578.211150 at c35g2000hsg.googlegroups.com>, Johny 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?
Because you can't change strings. Any function or method that "changes" a
string returns a new and modified copy. So does the `string.replace()`
function. And you don't bind the result to a name, so it is "lost".
This is shorter than using `replace()`:
In [9]: s = '12345 4343 454'
In [10]: s = s[:-1] + 'r'
In [11]: s
Out[11]: '12345 4343 45r'
BTW most things in the `string` module are deprecate because they are
available as methods on string objects.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list