ConfigParser: use newline in INI file

Chris Angelico rosuav at gmail.com
Sun Oct 2 06:46:06 EDT 2016


On Sun, Oct 2, 2016 at 9:34 PM, Thorsten Kampe
<thorsten at thorstenkampe.de> wrote:
>> If you want to have \n mean a newline in your config file, you can
>> do the conversion after you read the value:
>>
>>     >>> "a\\nb".decode("string-escape")
>>     'a\nb'
>
> Interesting approach (although it does not work with Python 3: decode
> is only for byte-strings and the string-escape encoding is not
> defined).
>
> If I understand this correctly, this is equivalent to
> `.replace('\\n', '\n')` ?

Yes, and a bunch of other conversions too. Notably, it will convert
'\\\\' into '\\' (I'd explain that with raw string literals but they
get wonky with trailing backslashes!), without breaking the
replacement of other constructs. But if you're okay with the string
r"\n" being impossible to enter, then go ahead and just use replace().
And you don't have to use \n specifically - if you're using replace(),
you can use any other token you like to separate lines. VX-REXX had a
nifty way to handle this: you may use any one-character separator you
like, simply by starting the string with it.

;foo;bar;quux;spam
!foo!bar!quux!spam
=foo=bar=quux=spam

If only a few of your tokens are multi-line, you could use this
technique - no escaping needed.

ChrisA



More information about the Python-list mailing list