简体   繁体   English

如何避免使用逗号分隔的字符串从python中的列表中加入引号

[英]How to avoid quotes from a comma separated string joined from a list in python

I have created a comma separated string by joining strings from a list in Python 3.5 and use it to write it to an INI file using configobj. 我通过在Python 3.5中连接列表中的字符串创建了一个逗号分隔的字符串,并使用configobj使用它将其写入INI文件。 Here is a sample Python script used in a Ubuntu 16.04 terminal: 这是在Ubuntu 16.04终端中使用的示例Python脚本:

sudo python3 << EOP
from configobj import ConfigObj

config=ConfigObj("myconfig.ini")
config['items']={}
itemlist=('item1','item2')
csvstr=",".join(list)
config['items']['itemlist'] = csvstr
config.write()
EOP

This writes the string with quotes as "item1,item2" as shown below. 如下所示,该字符串将引号括为“ item1,item2”。

[items]
itemlist = "item1,item2"

However, if the items are joined with other characters such as ";", it writes the string without quotes! 但是,如果项目与其他字符(例如“;”)连接在一起,则会写入不带引号的字符串! How to make it write the comma separated string without quotes? 如何使它写逗号分隔的字符串而不带引号?

Appreciate for any tips or solution. 感谢任何提示或解决方案。

Commas are reserved for field separation and so you cannot have (unless you really want to ) an unquoted string value with commas in it. 逗号保留用于字段分隔,因此您不能(除非您确实想要 )带有逗号的未引号的字符串值。 Apparently you do want to have a list of values, so just pass a list as the value: 显然,您确实希望有一个值列表,因此只需传递一个列表作为值:

from configobj import ConfigObj

config=ConfigObj("myconfig.ini")
config['items']={}
itemlist=['item1','item2']
config['items']['itemlist'] = itemlist
config.write()

This will result in 这将导致

[items]
itemlist = item1, item2

Another solution is to use the list_values keyword: 另一种解决方案是使用list_values关键字:

config = ConfigObj('myconfig.ini', list_values=False)

As the documentation says , if list_values=False then single line values are not quoted or unquoted when reading and writing. 如文档所述 ,如果list_values=False则在读取和写入时,单行值不加引号或不加引号。

The result: 结果:

[items]
itemlist = item1,item2

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

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