Python string corrupted with character

Asked

Viewed 3,104 times

1

I have a program that creates for your running another program on the user’s computer. In a snippet, I define the directory to which the new program will be intended as

 diret = "C:\\Users\\" + d_user

where d_user is the rest of the directory. However, when created and executed, the string is converted to

'C:\Users\' 

with only one bar, which raises

SyntaxError: EOL while scanning string literal 

because the string is not closed in the second ['].

How can I prevent this from happening in order for my code to be fully executed?

EDIT:

The code within the main code, which will be created, is available at https://ideone.com/KTAQxf lines 4 to 24; the others are only the context of the main code. The error occurs with line 10.

  • Can you give a full example that fails? I can’t reproduce the error.

  • @Pedrovonhertwig I updated, thank you in advance for any help.

1 answer

3


The line

diret = "C:\\Users\\" + d_user

is correct. What happens is that the \ is an escape character; that is, when you need for example to use quotes without finishing the string, you can do

s = "aspas: \" <- interpretado como aspas sem fechar a string"

Thus he is interpreted in a special way and he himself also needs to be escaped with \. When you want to put a character \ in the string, it is necessary to use \\ (the first "escapes" the second and the second is interpreted literally).

What you write in a new file is escaped, but therefore results in writing only one \ at a time. When the second file is read, there is only one \ and it escapes the double end quotes of the string.

To solve your problem, there are two possible solutions. The first is to bend the bars in the key_file.write:

...
diret = "C:\\\\Users\\\\" + d_user
...

And the second and perhaps more elegant is to use a raw string, or raw, prefixing it with r. Thus the \ is treated as a normal character.

key_file.write(r'''
    import sys
    [...]
    input()''')

Browser other questions tagged

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