4

I'd like to escape ":" and/or "=" as the name in a configuration file. Does anyone know how to achieve this? I try backslash "\", it does not work.

swimmingfisher
  • 901
  • 9
  • 9
  • could you be more specific. Do you want to remove all `:` and `=` from your config file? – Ashoka Lella Aug 08 '14 at 09:59
  • No, I want to use the colon as a part of one entry name in a configuration file. e.g. make "Checked in "D:\bla\bla" as the entry name in Checked in "D:\bla\bla=blabla – swimmingfisher Aug 11 '14 at 01:20

1 Answers1

8

If you're using Python 3, you don't need to. Look at the Python docs section on Customizing Parser Behavior. By default, configparser uses ":" and "=" as delimiters, but you can specify different delimiters when you create the configparser object:

import configparser

parser = configparser.ConfigParser(delimiters=('?', '*'))

In this example, the default delimiters have been replaced with a question mark and an asterisk. You can change the delimiters to whatever characters you want that won't conflict with the information you need to put in the config file.

The above listed method will only work for Python 3, as the Python 2 ConfigParser is hard-coded to recognize equal signs and colons as delimiters. According to this SO question, there is a backported configparser available for the 2.7 intepreter at https://pypi.python.org/pypi/configparser. See if that will work for you.

Community
  • 1
  • 1
skrrgwasme
  • 9,358
  • 11
  • 54
  • 84
  • 1
    Scott, thanks for you answer. While that may works for python 3, it always met below Error when using python 2.7, and it looks like the counterpart section on Customizing Parser Behavior can not be found in Python 2.7 docs. TypeError: __init__() got an unexpected keyword argument 'delimiters' – swimmingfisher Aug 11 '14 at 01:25
  • @DouglasGaskell What part doesn't work anymore? `delimiters` is still a valid input argument for `ConfigParser` objects [in 3.7.2](https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour). – skrrgwasme Jan 22 '19 at 16:12