pythonarrayspython-3.xmultidimensional-arraysplit

Separating a string into a 2d array using two different splits


I'm trying to input values into a CSV using a 2d array. I have a string which is separated by ',' to separate the values and ';' to separate each row.

string below;

text = 536924636,www.microsoft.com,http://www.microsoft.com/pkiops/crl/MicW;536924733,www.microsoft.com,http://www.microsoft.com/pkiops/certs/Mi;536925898,crl.microsoft.com,http://crl.microsoft.com/pki/crl/product;

I want to be able to split the rows into a 2d array like so

arr = reg.split([','][';'])

So that that it ends up like this;

arr =[ 
['536924636','www.microsoft.com','http://www.microsoft.com/pkiops/crl/MicW'],
['536924733','www.microsoft.com','http://www.microsoft.com/pkiops/certs/Mi'],
['536924636','www.microsoft.com','http://www.microsoft.com/pkiops/crl/MicW']]

but when I attempt this, I get the following error;

  arr = reg.split([','][';'])
TypeError: list indices must be integers or slices, not str

Solution

  • The function split() will split one string into one list. You can't make it produce two dimensions by passing it two parameters instead of one.

    But you can call it twice, once for each delimiter:

    >>> text = "536924636,www.microsoft.com,http://www.microsoft.com/pkiops/crl/MicW;536924733,www.microsoft.com,http://www.microsoft.com/pkiops/certs/Mi;536925898,crl.microsoft.com,http://crl.microsoft.com/pki/crl/product;"
    >>> [r.split(",") for r in [r for r in text.split(";")]]
    [
    ['536924636', 'www.microsoft.com', 'http://www.microsoft.com/pkiops/crl/MicW'], 
    ['536924733', 'www.microsoft.com', 'http://www.microsoft.com/pkiops/certs/Mi'], 
    ['536925898', 'crl.microsoft.com', 'http://crl.microsoft.com/pki/crl/product'], 
    ['']
    ]