simple string formatting question

N

Neal Becker

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?
 
B

Bruno Desthuilliers

Neal Becker a écrit :
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'

This should do what you want:

print " ".join("'%s'" % arg for arg in sys.argv)

NB : if your version of Python predates generator expressions, use a
list comp instead:

print " ".join(["'%s'" % arg for arg in sys.argv])
 
N

Neil Cerutti

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top