exec with n does not work

Asked

Viewed 80 times

0

I’m trying to use the function exec in a code that has \n, but it seems that this function does not support \n

a = '''
open('test.txt', 'a').write('Hello, world\n')
'''
exec(a) 

Error:

SyntaxError: EOL while scanning string literal

Is there any way to make it work?

2 answers

0


Yes - when the Python compiler reads the string that goes inside the vailable a, he already plays the \n to be a line change - then the code exec will compile at that point:

a = '''
open('test.txt', 'a').write('Hello, world\n')
'''
exec(a) 

is seen this way:

open('test.txt', 'a').write('Hello, world
')

What is a syntax error.

You resolve easily by escaping \ with an extra bar, or using a raw string:

a = r'''
open('test.txt', 'a').write('Hello, world\n')
'''
exec(a) 

(note the "r" prefixing the triple quotes in the a =) - this makes the "" in a is passed literately to the string, and when the compiler interprets the snippet write('Hello, world\n') inside, the n will be expanded, but this time in the right place.

  • there is some way to format this type of string?

-1

You’re trying to use exec specifically? Or could Voce write au document directly?

Like this: open('test.txt', 'a').write('Hello, world\n')

Any way, no comment '''. This is why Voce gets the error

Edited for your comment:

a = open('test.txt', 'a').write('Hello, world\n')
exec(str(a))
  • Yes, I needed to use exec

  • it makes no sense to run an expression and try to use exec in the result of the string transformed expression. In the case of things with side effect, such as this code, if it worked (and only depends on the representation of the object that was the result of the expression), you still run the risk of the effect happening twice.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.