简体   繁体   中英

exec() for multi-line string

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

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)
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 .

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM