[Tutor] Mutable String Question [java.lang.StringBuffer --> Python List]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon Aug 4 14:28:02 EDT 2003


> As D. Arnold already replied, the Pythonic way to do this is to suff
> your strings in a list and then use the join method as in:
>
> >>> word_list = ["My", "name", "is"]
> >>> print " ".join(word_list)
> My name is
> >>>
>
> This way you avoid the quadratic behaviour of concatening via + (due to
> allocation/deallocation I believe).
>
> If you *really* want mutable strings then the closest in the standard
> library that I can remember are the StringIO (cStringIO) and the mmap
> modules. Somewhere someone is bound to have coded a mutable string type
> for Python -- googling or the seraching in the vaults might turn up
> something.



Hi everyone,


Alternatively, if we want to treat our string as a list of characters,
then we can turn a string into a list of characters.  *grin* Here's an
example:


###
>>> sentence = "Python is a good programming language"
>>> buffer = list(sentence)
>>> buffer
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'g', 'o',
'o', 'd', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', ' ',
'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
>>>
>>>
###



We've "exploded" our string into its constituent characters.  Bam!
*grin* Now that we have a list of characters, we can do simple list
manipulation:

###
>>> buffer[12:16] = list('great')                ## Slice assignment
>>> buffer
['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 'a', ' ', 'g', 'r',
'e', 'a', 't', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g',
' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
###


List mainpulation is something that we're already pretty familiar with, so
this should be easy going.  *grin* Once we're done with our manipulation,
we can go back from our list of characters back into a string:

###
>>> ''.join(buffer)
'Python is a great programming language'
###



For comparison, the equivalent code in Java looks something like this:


///
String sentence = "Java is a good programming language";
StringBuffer buffer = new StringBuffer(sentence);
buffer.replace(10, 14, "fairly ok");
sentence = buffer.toString();
///


It's good to know that there's not much conceptual difference here.  If we
really look into Java's StringBuffer class:

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html

it becomes more clear that a Java StringBuffer is pretty much a "sequence"
of characters.  And since Lists are built into Python, there's less of a
need for an explicit "string buffer" class in Python --- Lists are often
powerful enough to do the job.


If you have more questions, please feel free to ask.  I hope this helps!





More information about the Tutor mailing list