Thread: join()

    #1
  1. Only the strong survives!!.
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Feb 2003
    Location
    A World of wonders.
    Posts
    5,583
    Rep Power
    407

    join()


    How do i use the string.join class with multydimentional arrays?

    Code:
    import string
    
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    join = string.join(matrix)
    print join
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    join only operates on strings
    http://www.python.org/doc/current/li...g-methods.html

    If you are trying to convert it to display the matrix as a string, try something like this

    Code:
    output = ""
    for row in matrix:
        for element in row:
            output += str(element) + ' '
        if len(row) > 0: output = output[:-1]
        output += '\n'
  4. #3
  5. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    For small lists of data this wouldn't be much of a problem but with HUGE lists this could be slow; because strings in Python are imutable the Python interpreter has to make copies of the strings when consinating them (string + string) and etc.

    This should work better:

    Code:
    #!/usr/bin/env python
    
    l = [[1,2,3],[4,5,6],[7,8,9]]
    j = []
    
    for s in l:
    	for e in s:
    		j.append(str(e))
    
    print ''.join(j)
    it only joins the data and doesnt display it in a matrix style like yogis does but you can do this is say.. one more line by appending a '\n' in there.

    Mark.
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo