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

Steven Howe howe.steven at gmail.com
Thu May 3 17:46:52 EDT 2007


Dave Borne wrote:
>> Let's suppose
>> s='12345 4343 454'
>> How can I replace the last '4' character?
>>     
>
> If the last '4' will not always be the last character in the string,
> you could do:
> 'X'.join(s.rsplit('4',1))
>   

    from string import rfind
    def replaceLast_X_with_Y( s, x, y ):
        lastX = s.rfind(x)
        return s[:lastX]+ y + s[lastX+1:]

    s = '12345 4343 454'
    replaceLast_X_with_Y( s, '4', '9' )
    '12345 4343 459'


sph

-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070503/a0684a5e/attachment.html>


More information about the Python-list mailing list