2

I have a class with instance attributes a,b,c. I used textwrap but it doesnt work.

 def __str__(self):
    import textwrap.dedent
    return textwrap.dedent(
    """#{0}
    {1}
    {2}
    """.format(self.a,self.b,self.c)

However, this is not working, and I am getting output like

a
        b
        c
1
  • 1
    textwrap.dedent gets rid of common leading whitespace. This means that each line must have the same whitespace in front of it. Clearly, your first line, "#{0}... does not. Commented Oct 24, 2014 at 13:20

3 Answers 3

6

When you render a string with """, both newlines AND whitespaces are counted. If you want this to work without dedent, your code should look like this:

def __str__(self):
   return """#{0}
{1}
{2}
""".format(self.a,self.b,self.c)

Otherwise, the tabs before {1} and {2} are in the string as well. Alternatively, you could use:

"#{0}\n{1}\n{2}\n".format(self.a,self.b,self.c)

Regarding dedent and why it's not working, note this line from the documentation:

the lines " hello" and "\thello" are considered to have no common leading whitespace.

So if you want dedent to work, you need each line to start the same, so your code should be:

    return textwrap.dedent(
    """\
    #{0}
    {1}
    {2}
    """.format(self.a,self.b,self.c))

And in this case each line starts with \t, which dedent recognizes and removes.

Sign up to request clarification or add additional context in comments.

Comments

3

Do it like this:

from textwrap import dedent

def __str__(self):
    return textwrap.dedent("""\
        #{0}
        {1}
        {2}
        """.format(self.a,self.b,self.c))

Comments

0

textwrap.dedent strips common leading whitespace (see documentation). If you want this to work, you'll need to do something like this:

def __str__(self):
    S = """\
        #{0}
        {1}
        {2}
    """
    return textwrap.dedent(S.format(self.a, self.b, self.c))

1 Comment

Thanks. I totally missed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.