Raj Raj - 2 months ago 7
Python Question

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. Here is a sample Python script used in a Ubuntu 16.04 terminal:

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.

[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.

Answer

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
Comments