Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list to string with prefix and suffix

Tags:

python

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?

like image 394
Johnny Avatar asked Oct 27 '25 05:10

Johnny


2 Answers

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")
like image 70
grc Avatar answered Oct 28 '25 18:10

grc


Using a generator expression:

print  "cat " + " ".join("file%d.txt" % int(d) for d in mylist) + " > result.txt"
like image 20
perreal Avatar answered Oct 28 '25 20:10

perreal