Home > OS >  What is causing "triple quotes" to change the indentation?
What is causing "triple quotes" to change the indentation?

Time:10-14

I am using triple quotes to create a multiline string:

print(
    ''' Hello!
        How are
        you?''')

Output:

 Hello!
        How are
        you?

Inside the string, How is coming exactly underneath Hello.

However, I am not able to understand what is causing the indentation to change.

CodePudding user response:

To answer the question, the number of spaces inside the string are exactly correct, triple quoting is not changing indentation.

To answer the question behind the question, use textwrap.dedent if you want to remove common leading whitespace so that multiline strings still line up nicely in the source code:

>>> print(dedent('''\
...           Hello!
...           How are
...           you?'''))
Hello!
How are
you?

You may be interested also to follow Compile time textwrap.dedent() equivalent for str or bytes literals.

CodePudding user response:

When you use triple quotes like this, the resulting string will contain all of the characters between the triple quotes, including spaces and line breaks.

So, let's look at your code again. It looks like this:

    ''' Hello!
        How are
        you?'''

If we look closely at this code, we can see that it consists of:

  • 4 spaces
  • The triple quotation mark '''
  • 1 space
  • The word Hello!
  • A line break
  • 8 spaces
  • The words How are
  • A line break
  • 8 spaces
  • The word you?
  • The triple quotation mark '''

Therefore, the resulting string will contain all of the characters between the triple quotes, namely:

  • 1 space
  • The word Hello!
  • A line break
  • 8 spaces
  • The words How are
  • A line break
  • 8 spaces
  • The word you?

And as you can see, that's exactly what got printed out.

CodePudding user response:

Let's look at the Python docs:

Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points. String literals are written in a variety of ways:

Single quotes: 'allows embedded "double" quotes'

Double quotes: "allows embedded 'single' quotes".

Triple quoted: '''Three single quotes''', """Three double quotes"""

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

I'm not sure what your desired output is, but the short answer is that Python interprets whitespace inside triple-quotes literally; that's why it's included in the printed output.

CodePudding user response:

try this

print(f''' 
Hello!
How are
you?''')
  • Related