[Tutor] Decision matrix

Jeff Shannon jeff@ccvcorp.com
Thu Feb 13 13:04:02 2003


Erik Price wrote:

>
> [1] Is a string really a list of characters, or does it just allow you 
> to treat it as one?  Anyone know? 


Not quite -- a string is a *sequence* of characters.  Lists and tuples 
are also sequences.  There's similarities, but also differences.  For 
instance, any sequence can be used in a for loop.  However, lists are 
the only (built-in) sequence that can be sorted.  It is pretty easy to 
convert between these sequences, however.

 >>> mystring = "eggsandspam"
 >>> mylist = list(mystring)
 >>> mylist
['e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm']
 >>> mytuple = tuple(mystring)
 >>> mytuple
('e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm')
 >>> mytuple = tuple(mylist)
 >>> mytuple
('e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm')
 >>> myotherstring = ''.join(mytuple)
 >>> myotherstring
'eggsandspam'
 >>> myotherotherstring = ''.join(mylist)
 >>> myotherotherstring
'eggsandspam'
 >>>

Converting a (non-string) sequence to a string is a little bit different 
from converting to a list or tuple, but the principle is still there. 
 You might ask why you can't just use the string constructor function, 
str(), to convert to a string, in the same way that you use the list() 
and tuple() constructors.  Well, the answer is that you *can*, but the 
results may not be quite what you want:

 >>> str(mylist)
"['e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm']"
 >>>

It creates a string representation of the list, rather than a string 
containing the elements of the list.  The request "make a string out of 
this list" is somewhat ambiguous in this case, and Python has chosen to 
resolve that ambiguity in a practical way -- especially since the 
string.join() method would be desirable anyhow, and the list that you're 
asking to convert might not contain only characters.

Jeff Shannon
Technician/Programmer
Credit International