我需要处理一个python列表,如下所示:
PGPrimary=['VDD', 'VSS', 'A', 'Y']
我需要将此列表更改为以下格式:
//PG PRIMARY ("VDD") ("VSS") ("A") ("Y")
我尝试了以下代码,但它不起作用:
PGPrimary=['VDD', 'VSS', 'A', 'Y']
print("1:PGPrimary:",PGPrimary)
PGPrimary="//PG PRIMARY " + ' '.join(PGPrimary)
(','.join('("' + item + '")' for item in PGPrimary))
print("2:PGPrimary:",PGPrimary)
这是输出:
('1:PGPrimary:', ['VDD', 'VSS', 'A', 'Y'])
('2:PGPrimary:', '//PG PRIMARY VDD VSS A Y')
进程已完成,退出代码为 0
谁能指出为什么代码不起作用?
str.format
和 str.join
:
'//PG PRIMARY {}'.format(' '.join('("{}")'.format(i) for i in PGPrimary))
'("{}")'.format(i) for i in PGPrimary)
循环访问列表元素,并在每个元素周围添加括号和引号' '.join
连接上述生成的可迭代对象
例:
In [33]: PGPrimary=['VDD', 'VSS', 'A', 'Y']
In [34]: '//PG PRIMARY {}'.format(' '.join('("{}")'.format(i) for i in PGPrimary))
Out[34]: '//PG PRIMARY ("VDD") ("VSS") ("A") ("Y")'
试试这个:
PGPrimary=['VDD', 'VSS', 'A', 'Y']
print("1:PGPrimary:",PGPrimary)
PGPrimary="//PG PRIMARY " + ' '.join('("' + item + '")' for item in PGPrimary)
print("2:PGPrimary:",PGPrimary)