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?
– João