Johnny
Johnny

Reputation: 512

Converting a list to string with prefix and suffix

I have this list:

myist = ['0', '1', '2', '3']

and I want to execute something via os.system() where multiple files are used in one line:

cat file0.txt file1.txt file2.txt file3.txt > result.txt

but I'm not sure how to add a suffix when joining the list. This:

os.system("cat file" + ' file'.join(mylist) +".txt > result.txt" )

will give me:

cat file0 file1 file2 file3.txt > result.txt

but what I want is this:

cat file0.txt file1.txt file2.txt file3.txt > result.txt

So what I'm searching for is something like 'prefix'.join(mylist).'suffix'. How can I do this without using for loops?

Upvotes: 4

Views: 14315

Answers (3)

RMcG
RMcG

Reputation: 1095

In case you every want to use it for more than 4 items

os.system('cat %s > result.txt'%(' '.join("file%i.txt"%i for i in xrange(0,4))))

you could also do:

mylist = ['0','1','2','3']
os.system('cat %s > result.txt'%(' '.join("file%s.txt"%i for i in mylist)))

but that's less fun.

Upvotes: 1

perreal
perreal

Reputation: 97958

Using a generator expression:

print  "cat " + " ".join("file%d.txt" % int(d) for d in mylist) + " > result.txt"

Upvotes: 4

grc
grc

Reputation: 23575

You could just add the suffix to the start of the string:

os.system("cat file" + '.txt file'.join(mylist) +".txt > result.txt")

Or you could use string formatting with the map function:

os.system("cat " + ' '.join(map('file{0}.txt'.format, mylist)) + " > result.txt")

Upvotes: 5

Related Questions