[Tutor] Replace a character by index

Christian Witts cwitts at compuscan.co.za
Thu Jul 16 11:32:01 CEST 2009


Wayne wrote:
> On Thu, Jul 16, 2009 at 4:06 AM, Christian Witts 
> <cwitts at compuscan.co.za <mailto:cwitts at compuscan.co.za>> wrote:
>
>     <snip> 
>
>     Strings are essentially a list already of characters.  What would
>     be slowing down your preferred method #1 would be your explicit
>     cast to a list and then re-joining that list.  Strings support
>     item assignment so you can save quite a few cycles just doing
>
>     word = 'cat'
>     word[1] = '_'
>
>
> Not in python they don't!
> In [97]: word[1]='_'
> ---------------------------------------------------------------------------
> TypeError                                 Traceback (most recent call 
> last)
>
> /home/wayne/programming/python/sight_words/<ipython console> in <module>()
>
> TypeError: 'str' object does not support item assignment
>
> But of course I already knew that from experience :-P
>  
> -Wayne
>
Whoops, early morning, lack of coffee, some deadlines on my head to 
blame for that. :p

Rebuilding strings would be faster using concatenation than casting to 
list and joining, it is the method I prefer when cutting things out.  I 
also find it looks neater and is easier to read.  Also '%s%s%s' % 
(a[:idx], '_', a[idx+1:]) would be preferred over a[:idx] + '_' + a[idx+1:]

-- 
Kind Regards,
Christian Witts




More information about the Tutor mailing list