optimum way of assigning to a string slice

Ype Kingma ykingma at accessforall.nl
Sat Jan 11 03:57:12 EST 2003


Jonathan P. wrote:

> I'm creating a text widget input control in the form of a
> class, called EditField, and it has, as a class member, a string
> EditField.content, containing the current input.  Everytime
> the user types in a new character, I have to modify EditField.content
> to reflect the letter the user typed in.
> 
> The clearest way I can think of doing this would be something like:
> 
> self.content[cursorpos:cursorpos+1]=keypress
> 
> Of course, this won't work because of string immutability.
> Thus the workaround would be to create a newstring:
> 
> self.content=self.content[0:cursorpos]+keypress+self.content[cursorpos+1:]
> 
> Is there a better, more efficent way?

When you need to do many such operations you can represent the whole
string by a list of substrings and delay the concatenation (the + operator
in your example) until you need the string itself. You can then slice
the list, but you'll have to take into account the lenghts of the 
substrings, evt. replacing them by other substrings.
Afterwards you can ''.join(substrings) instead of using +.

In this case I don't think using a list of substring is more efficient.

There are several implementations of mutable strings for python (iirc
there is one in the CSstringIO module), but they don't seem to gain
enough popularity to make it into a standard type.
In case you use jython, you can also resort to java's StringBuffer,
which is a mutable string.

Have fun,
Ype

-- 
email at xs4all.nl




More information about the Python-list mailing list