0

I'm trying to parse a list of values for a key using ConfigParser in Python 3.

I saw that it is possible using the JSON library and Python lists in the config file (Lists in ConfigParser):

[sites]
urls = ["https://google.com", "https://yahoo.com", "https://gmail.com"]

Is it possible to set a delimiter instead? Example, using a colon delimiter:

[sites]
urls=https\://google.com:https\://yahoo.com:https\://gmail.com

2 Answers2

0

You could simply split on a separator of your choice applicable for your list of URLs, e.g.:

import configparser

if __name__ == '__main__':
    parser = configparser.ConfigParser()
    parser.read_string("""
    [sites]
    urls=https://google.com;https://yahoo.com;https://gmail.com
    """)

    sites = parser['sites']['urls'].split(';')
    print(sites)  # prints ['https://google.com', 'https://yahoo.com', 'https://gmail.com']

Keep in mind that semicolons might be part of URLs. Therefore, a different separator might be a better choice for you.

oschlueter
  • 2,596
  • 1
  • 23
  • 46
0

Based on oschlueter's answer and Nick ODell's comment, the following does the job:

[s.replace('\\','') for s in re.split(r'(?<!\\):', parser['sites']['urls'])]

re.split returns the capture group – the negative lookbehind in this case – so you need to remove it with str.replace.

>>> import re
>>> from configparser import ConfigParser
>>> parser = ConfigParser()
>>> parser.read('config.ini')
['config.ini']
>>> [s.replace('\\','') for s in re.split(r'(?<!\\):', parser['sites']['urls'])]
['https://google.com', 'https://yahoo.com', 'https://gmail.com']

EDIT:

Works with other delimiters too:

urls_at=https://google.com/\@@https://yahoo.com/\@@https://gmail.com/\@
urls_semicolon=https://google.com/\;;https://yahoo.com/\;;https://gmail.com/\;
>>> [s.replace('\\','') for s in re.split(r'(?<!\\);', parser['sites']['urls_semicolon'])]
['https://google.com/;', 'https://yahoo.com/;', 'https://gmail.com/;']
>>> [s.replace('\\','') for s in re.split(r'(?<!\\)@', parser['sites']['urls_at'])]
['https://google.com/@', 'https://yahoo.com/@', 'https://gmail.com/@']