convert string to list

Cliff Wells clifford.wells at comcast.net
Fri Oct 15 07:09:23 EDT 2004


On Fri, 2004-10-15 at 10:15 +0200, Josef Meile wrote:

> > 
> Why not just:
> 
> script.py "a, b, c" "d, e, f"
> 
> Then:
>  > arglist = []
>  > for arg in sys.argv[1:]:
>  >     arglist.append(arg.split(','))
> 
> Better than eval.

A basic problem is that the OP gave no indication of what would really
be passed as the lists (well, I'm assuming that his examples of ['A',
'B', 'C'] were contrived for simplicity).  Without knowing this, then
it's impossible to know if a character such as ',' might be contained in
the data.  If it is then splitting on ',' is going to fail.  A better
approach might be to pass the info as valid CSV data and use the csv
module to evaluate it:

#!/bin/bash
python bar.py '"a","b","c"' '"d","e","f"'


#!/usr/bin/python
import sys, csv
from StringIO import StringIO

for arg in sys.argv[1:]:
    reader = csv.reader(StringIO(arg))
    for row in reader:
        print row


Regards,
Cliff

-- 
Cliff Wells <clifford.wells at comcast.net>




More information about the Python-list mailing list