이시인 이시인 - 3 months ago 25
Python Question

Python textwrap.dedent with comment does not work as expected

I'm using Python 3.6 on visual studio.
Below is python interactive log

>>> from textwrap import dedent
>>> dedent("\ta = 4\n")
'a = 4\n'
>>> dedent("\ta = 4\n#")
'\ta = 4\n#'
>>> dedent("\ta = 4\n\t#")
'a = 4\n#'
>>> dedent("\ta = 4\n\t\n#")
'\ta = 4\n\n#'
>>> dedent("\ta = 4\n\t\n\t#")
'a = 4\n\n#'
>>> dedent("\ta = 4\n\t#\n\t")
'a = 4\n#\n'
>>> dedent("\ta = 4\n\t\n#\t")
'\ta = 4\n\n#\t'
>>>


dedent properly unindents leading tab on first case, but when i added '#', leading tab does not unindents. Is this intended?

Answer Source

textwrap.dedent() assumes its argument is plain text, not Python source code. It doesn't interpret "#" as a comment.

These two examples will behave similarly:

>>> dedent("\ta = 4\n#")
'\ta = 4\n#'
>>> dedent("\ta = 4\nx")
'\ta = 4\nx'