Created
December 21, 2019 09:04
-
-
Save Jasata/e2246c64fd87cc3691ecc097d063a0a4 to your computer and use it in GitHub Desktop.
Configparser list-value clean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# Snippet for cleaning out configuration file list-values (import configparser). | |
# For reading/processing configuration file values, performance is not an issue. | |
# The key = value can sometimes look something like: | |
# | |
# files = , data.db ,script.py, ,, data.db ,,, | |
# | |
# NOTE: Neither of these can deal with quotations (" or ') and thus cannot process | |
# list items that need to have the separator (,) in them. | |
# | |
files = ",/tmp/x = b ,data.db ,script.py, ,, data.db ,,," | |
def val2list(val: str) -> list: | |
"""NOTE: Order is not preserved.""" | |
return list(set([x.strip() for x in val.split(",") if x.strip()])) | |
def val_to_list(val: str) -> list: | |
"""Python 3.7+ solution (dictionaries are guaranteed to maintain order).""" | |
return list(dict.fromkeys([x.strip() for x in val.split(",") if x.strip()])) | |
print(val2list(files)) | |
print(val_to_list(files)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment