Title: textwrap.dedent doesn't work properly with embedded strings containing linefeeds
Type: Stage: resolved
Components: Versions:
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: mdear, ned.deily
Priority: normal Keywords:

Created on 2015-02-22 00:57 by mdear, last changed 2015-02-22 01:19 by ned.deily. This issue is now closed.

Messages (2)
msg236396 - (view) Author: Myles Dear (mdear) Date: 2015-02-22 00:57
The textwrap.dedent function does not work when the string to dedent itself contains embedded strings that contain newline characters. states that this function "can be used to make triple-quoted strings line up with the left edge of the display".

It just so happens that my triple-quoted string itself contains a single-quoted string with newline characters.  I would have expected textwrap.dedent to ignore these newline characters inside single or double quoted strings contained in the larger triple-quoted string.

The semantics of this bug may be slightly different than "textwrap.dedent doesn't work properly with strings containing CRLF", so I'm raising a new issue.

I am seeing this in a module I'm writing that emits synthetic python code that is subsequently passed back into the interpreter via "exec".

Python 3.4.1 (default, Nov 12 2014, 13:34:29) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from textwrap import dedent
>>> s = '''
...     'my_key' : r'my value which contains \n character'
... '''
>>> s
"\n    'my_key' : r'my value which contains \n character'\n"
>>> dedent(s)
"\n   'my_key' : r'my value which contains \ncharacter'\n"
msg236398 - (view) Author: Ned Deily (ned.deily) * (Python committer) Date: 2015-02-22 01:19
If you do not want the `\n` to be interpreted as a linefeed, you need to use a raw string literal, like:

a = r'''
...     'my_key' : r'my value which contains \n character'
... '''
>>> print(dedent(a))

'my_key' : r'my value which contains \n character'
Date User Action Args
2015-02-22 01:19:25ned.deilysetstatus: open -> closed

nosy: + ned.deily
messages: + msg236398

resolution: not a bug
stage: resolved
2015-02-22 00:57:55mdearcreate