[Tutor] Replace a character by index
Gregor Lingl
gregor.lingl at aon.at
Thu Jul 16 11:22:35 CEST 2009
Christian Witts schrieb:
> Wayne wrote:
>> Hi,
>> ...
>> ------------------------------------------------------------------------
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> 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] = '_'
>
> which would result in word printing 'c_t'.
That's simply not true in Python. Try it out!
>>> word = "cat"
>>> word[1] = "_"
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
word[1] = "_"
TypeError: 'str' object does not support item assignment
>>>
Gregor
> I'm assuming your use case would be just a call to random with bounds
> zero -> length of string - 1 and then using that index to replace the
> character with an underscore and it is much simpler and faster to just
> use the strings build in index and item assignment.
>
> Hope that helps.
>
More information about the Tutor
mailing list