[Tutor] arrays and strings

Erik Price erikprice@mac.com
Mon, 6 May 2002 21:45:44 -0400


On Monday, May 6, 2002, at 11:14  AM, wonderer@pakistanmail.com wrote:

> Hi can some one tell me how can we convert arrays to strings in python.
> I have seen functions like repr()and tostring() etc.
> I do it like this
> def funcA ():
>  declare some array and assign some values
>  ....
>  showvalues(repr(array))
>
> def showvalues(temp):
>  for index in range (0,5,1):
>   print "value ",temp[index]
>
> and it never shows me the values that i inserted but shows the 
> declaration of
> array element like a,r,r,y,(,",l,") and so on with elements.
> what i was really trying to do was use an array(of type we use in c) 
> and then
> send that array to some function for processing but the dispaly is 
> never as
> i want it to be.

I'm not really sure exactly what the difference is myself, but I keep 
hearing that arrays are not the same thing as lists, so you may be 
referring to lists.  I think it has something to do with the way memory 
is allocated.  (I'm used to saying arrays too... ssh!)

I'm curious as to why you would be using the repr() function -- it's a 
very useful tool for debugging, but you rarely want to see the canonical 
representation* of something in an application (as an end user).

* http://www.tuxedo.org/~esr/jargon/html/entry/canonical.html

I think that what you want to do is simply join the elements of a list 
together into one string?  Well, there is an easy way to do this -- 
simply use the join method of string objects to concatenate a sequence 
of strings together:

 >>> mylist = ['item1', 'mutant', 'item3', 'indexnumber4']
 >>> string = ' '.join(mylist)
 >>> string
'item1 mutant item3 indexnumber4'

See what that does?  It takes the string object (a space, in this case, 
located between quotes) and uses it as the separator of a sequence of 
other strings (which in this case is "mylist").  This does exactly what 
you want, I think.  Remember that it only works in joining a sequence of 
strings, which means you have to convert the elements of a list into 
strings if you want to use the join() method on integers or some other 
data type.

Erik