pythonarrays

print elements in an array with a delimiter


I am new to Python and I have become stuck with printing the elements of an array separated by a delimiter. My array consists of 60 000 odd rows with 26 elements per row, some of the elements only contain numbers, while others contain an assortment of characters including special characters. Example:

a[0] = [abc,123,a1b2c3,*wewqe,...] 
a[1] = [098i,qwerty,123qwe,xx-u,...]

I would like the output to be(without a "|" after the last element and each row on their own line:

abc|123|a1b2c3|*wewqe,...
098i|qwerty|123qwe|xx-u,...

I have tried the following, but they do not work:

for row in results :
    length = len(row)
    print("")#throw in a new line
    print ("Number of elements: " + str(length))
    print '|'.join((str(row)))

And this:

for row in results :
    length = len(row)
    print("")#throw in a new line
    print ("Number of elements: " + str(length))
    for item in row:
            print '|'.join(str(item))

And this:

 for row in results :
    length = len(row)
    print("")#throw in a new line
    print ("Number of elements: " + str(length))
    for item in row:
    print item,

All of the above produces results, but not the results I would like. Thank you in advance.


Solution

  • print '|'.join(map(str, row))
    

    join takes a sequence of strings. row is a sequence of... something, so map(str, row) turns it into a sequence of strings. If the elements of row are already strings (and they should be), you can just do

    print '|'.join(row)
    

    On Python 3, you can still use '.'.join, or you can use the sep argument to Python 3's print function:

    print(*row, sep='|')
    

    which will tell print to put a | between printed items instead of the usual space.