0

How can I obtain the expected result below?

import glob
infiles = glob.glob('E:\\test\\*.txt')
print infiles
['E:\\test\\a.txt', 'E:\\test\\b.txt', 'E:\\test\\c.txt', 'E:\\test\\d.txt']

Expected result is:

'E:\\test\\a.txt','E:\\test\\b.txt','E:\\test\\c.txt','E:\\test\\d.txt'

My attempt is:

infiles = ','.join(x for x in infiles)
print infiles
E:\test\a.txt,E:\test\b.txt,E:\test\c.txt,E:\test\d.txt

2 Answers 2

3
print ','.join(map(repr, infiles))

You're looking for an output containing the repr representations of the strings in the lists, not the literal character contents of the strings. Mapping repr over the list gets you that.

Sign up to request clarification or add additional context in comments.

Comments

1

Simply:

import glob
infiles = glob.glob('E:\\test\\*.txt')
print infiles.__str__()[1:-1]

print is actually print infiles.__str__() under the hood, and you only want to get rid of the [ and ]...

3 Comments

Rather than directly calling the magic method, it's generally preferable to use the str built-in. Aside from stylistic issues, it correctly falls back to __repr__ when __str__ isn't present. That happens to not be an issue for lists, but remembering which types implement which magic methods is an unnecessary hassle.
Also, this results in spaces in the output that the desired output doesn't have. That might be an issue, or it might be unimportant.
@user2357112, Thank you for the very helpful suggestion of str(infiles).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.