simple string formatting question

Neil Cerutti horpner at yahoo.com
Fri Dec 14 11:01:24 EST 2007


On 2007-12-14, Neal Becker <ndbecker2 at gmail.com> wrote:
> I have a list of strings (sys.argv actually).  I want to print them as a
> space-delimited string (actually, the same way they went into the command
> line, so I can cut and paste)
>
> So if I run my program like:
> ./my_prog a b c d
>
> I want it to print:
>
> './my_prog' 'a' 'b' 'c' 'd'
>
> Just print sys.argv will almost work, but it's comma-delimited.
>
> There must be some clever way to do this.  Any ideas?

The csv module is clever. Try the following:

import sys
import csv

writer = csv.writer(sys.stdout, delimiter=' ', quotechar="'", 
                    quoting=csv.QUOTE_ALL)
writer.writerow(sys.argv)

You might want to set a few more of the dialect options, too,
e.g., in case an arg contains a '.

The shutil module might contain something more specialized.

-- 
Neil Cerutti



More information about the Python-list mailing list