[Python] Proper tab indentation of multiline strings in Python [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to execute Python code dynamically. Hence I want to create a string representation of a piece of code that feeds into a exec function. However, I am having problem representing the code (with proper tab spaces) as a multiline string. The following shows the problem:

    multiline = """
    foo
    bar
    """
    print(multiline)

    output:
    foo
    bar


    This is expected behaviour. However, if I want to use implicit string continuation using () like so:

    multiline = (
    "foo\n"
    "\tbar"
    )
    print(multiline)
    output:
    foo
    bar


    The output seems to come with an extra tab space inserted, even though I used a single \t in the string. What am I missing here?

    Continue reading...

Compartilhe esta Página