Home > Mobile >  exec() for multi-line string
exec() for multi-line string

Time:11-22

This works:

s = "for x in range(5):" \
    "print(x)"
exec(s)

How to add if statement to that dynamic code, something like:

s = "for x in range(5):" \
    "if x>2:" \
    "print(x)"
exec(s)

Above gives error:

...
for x in range(5):if x > 2:print(x)
                   ^
SyntaxError: invalid syntax

CodePudding user response:

The problem is the lack of proper indentation of the code in the string. An easy way to get it right is to enclose the properly formatted code in a triple-quoted string.

s = """
for x in range(5):
    if x>2:
        print(x)
"""
exec(s)

CodePudding user response:

note that \ is only python's way of allowing visually continuing the same declaration at a "new line". so in practice,

s = "for x in range(5):" \
    "if x>2:" \
    "print(x)"

is equal to

s = "for x in range(5):if x>2:print(x)"

You will need to add actual line breaks and tabs to make the syntax valid, as such:

s = "for x in range(5):\n\tif x>2:\n\t\tprint(x)"

note that you can make it more readable if you combine \ with the above, and swapping \t with spaces, resulting in:

s = "for x in range(5):" \
    "\n if x>2:" \
    "\n  print(x)"

(Note that to confirm with PEP-8, you should use 4 spaces per identation)

CodePudding user response:

s = "for x in range(5):\n\t" \
    "if x > 2:\n\t\t" \
    "print(x)"
exec(s)

This will solve your problem. The reason for getting error is ignoring the python indentation rule, so you need to handle them with \t.

  • Related