繁体   English   中英

在列表的每个元素中添加引号和方括号

[英]Add quotes and brackets to every element of a list

我需要处理如下的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.formatstr.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)

暂无
暂无

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

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