ILostMySpoon
ILostMySpoon

Reputation: 2409

Python string formatting within list

What is best way to achieve the following? Each of the elements in the list needs to be appended with a common string.

path = os.path.join(os.path.dirname(__file__), 'configs'))

files = ['%s/file1', '%s/file2'] % path

But I am getting the following error:

TypeError: unsupported operand type(s) for %: 'list' and 'str'

Upvotes: 0

Views: 52

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121296

You need to apply it to each format in turn:

files = ['%s/file1' % path, '%s/file2' % path]

However, you should really use os.path.join() here; then the correct platform-specific directory separator will be used, always:

files = [os.path.join(path, 'file1'), os.path.join(path, 'file2')]

If this is getting repetitive, use a list comprehension:

files = [os.path.join(path, f) for f in ('file1', 'file2')]

Upvotes: 2

Related Questions