0

I am passing list as a argument (sys.argv) like:

 >>>python test.py ["1/1/2015","1/2/2015"] 

Which is received as:

>>>print sys.argv[1]
[1/1/2015,1/2/2015]  

Expected output:

>>>print sys.argv[1]
["1/1/2015","1/2/2015"]  

My attempt:

param=(', '.join('"' + item + '"' for item in sys.argv[1]))
print param  

Output is something like:

"[", "1", "/", "1", "/", "2015", ",", "1", "/", "2015", "2", "]"  

What is a correct way of adding double quotes in each elements of list in Python ?

  • 1
    is it mandatory to pass the dates in that format or can you pass them as `1/1/2015 1/2/2015`? – Pynchia Nov 16 '15 at 21:29
  • Or even, pass in as `1/1/2015,1/2/2015` allowing other parameters. Then you can just split by `,` to get each date. – Sam McCreery Nov 16 '15 at 21:35
  • btw: list elements have no quotes. print add quotes when you `print some_list` to distinguish text "123" from number 123. – furas Nov 16 '15 at 21:40

3 Answers3

0

Your input is in fact a string and not a list, therefore your approach ends up iterating over each character. If you want to get an array, you can use the following code:

param=[item for item in sys.argv[1][1:-1].split(",")]
print param  

The output is:

['1/1/2015', '1/2/2015']
Alex
  • 19,061
  • 10
  • 50
  • 66
0

I think you're doing it generally right.

x = 'stuff'
=> print x
stuff
=> x = '"' + x +'"'
=> print x
"stuff"

The problem seems to be that your sys.argv[1] isn't a list, it's a string.

From this post:

=> import ast
=> x = u'[ "A","B","C" , " D"]'
=> x = ast.literal_eval(x)
=> x
['A', 'B', 'C', ' D']
=> x = [n.strip() for n in x]
=> x
['A', 'B', 'C', 'D']

So:

x = sys.argv[1]
# for this to work, sys.argv[1] has to be u'["1/1/2015","1/2/2015"]'
# the inside quotes are important
x = ast.literal_eval(x)
for each in x:
    each = '"' + each + '"'
Community
  • 1
  • 1
NotAnAmbiTurner
  • 1,730
  • 1
  • 16
  • 38
0

You are not passing list as argument but always string. If you really just want expected output (not real python list) call your script like this:

python test.py [\"1/1/2015\",\"1/2/2015\"] 
poko
  • 577
  • 2
  • 7