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

Matimus mccredie at gmail.com
Thu May 3 10:52:17 EDT 2007


On May 3, 7:44 am, Johny <pyt... at hope.cz> wrote:
> On May 3, 4:37 pm, kyoso... at gmail.com wrote:
>
>
>
> > 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
>
> Mike it does NOT work for me.>>> s.replace(s[len(s)-1], 'r')
>
> '123r5 r3r3 r5r'
>
> I need only the last character to be replaced

Its not working because str.replace:

[docstring]
Help on method_descriptor:

replace(...)
    S.replace (old, new[, count]) -> string

    Return a copy of string S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
[/docstring]

Notice the "all occurrences of substring" part. Strings are immutable,
so there isn't really any replace, either way you are going to be
creating a new string. So the best way to do what (I think) you want
to do is this...

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




More information about the Python-list mailing list