简体   繁体   English

列表中的Python字符串格式

[英]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'

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; 但是,您实际上os.path.join()在这里使用os.path.join() 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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM