[Tutor] working with strings in python3

Steve Willoughby steve at alchemy.com
Tue Apr 19 16:29:20 CEST 2011


On 19-Apr-11 06:44, Rance Hall wrote:
> On Mon, Apr 18, 2011 at 9:50 PM, Marc Tompkins<marc.tompkins at gmail.com>  wrote:
>> On Mon, Apr 18, 2011 at 6:53 PM, Rance Hall<ranceh at gmail.com>  wrote:

> I think you misunderstood me, I simply meant that the print "
> ".join(message) has to parse through each word in order to get any
> output, I didn't mean to suggest that you got output one word at a
> time.  Sorry for the confusion.

Not quite true.  join() doesn't need to parse through words or anything. 
  It takes a list of strings and efficiently copies them into a new 
large string.  Maybe you're thinking of split() or something?

> I'm not sure I buy this explanation as strings have been used as keys
> in dictionaries or "associative arrays" for a long time, a string
> variable is variable or mutable, where a keyname can not be.

You're forgetting that you're not talking about a string VALUE like in 
most other languages, but rather a string OBJECT.  In C, if you store a 
value in a hash table with a string key, that key doesn't change even if 
the variable it came from takes a new value.  So it doesn't upset the 
key at all.

In Python, the string OBJECT you use may still be referenced by a 
variable, so if you were to mutate that string object, it would change 
and ALL variables referring to it would see the change, including the 
hash table structure which forms the dictionary.  In this sense, think 
of Python variable names more like C's pointers (sort of).  It's the 
same effect you'd get if you kept a pointer (in C) to the string value 
you stored your data in a hash table there, then went through that 
pointer to corrupt the hash table after the fact.

I'm not sure if your background in programming includes those concepts 
(I'm assuming so) or if I explained that clearly enough, but that 
illustrates why Python string OBJECTS need to be immutable (as are 
simple numeric OBJECTS.  The confusion that trips a lot of new Python 
programmers is that Python variables don't work like other languages, 
they're more of a blending of "variables", "pointers" and "references" 
which just "do the right thing" most of the time due to how Python 
manages variable access.  But they are not quite the same as any of 
those in other languages.

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list