Python ConfigParser - values between quotes

Davey picture Davey · Aug 21, 2009 · Viewed 15.4k times · Source

When using ConfigParser module I would like to use values containing of multiple words set in cfg file. In this case seems trivial for me to surround the string with quotes like (example.cfg):

[GENERAL]
onekey = "value in some words"

My problem is that in this case python appends the quotes to the string as well when using the value like this:

config = ConfigParser()
config.read(["example.cfg"])
print config.get('GENERAL', 'onekey')

I am sure there is an in-built feature to manage to print only 'value in some words' instead of '"value in some words"'. How is it possible? Thanks.

Answer

Mark Rushakoff picture Mark Rushakoff · Aug 21, 2009

I didn't see anything in the configparser manual, but you could just use the .strip method of strings to get rid of the leading and trailing double quotes.

>>> s = '"hello world"'
>>> s
'"hello world"'
>>> s.strip('"')
'hello world'
>>> s2 = "foo"
>>> s2.strip('"')
'foo'

As you can see, .strip does not modify the string if it does not start and end with the specified string.