\ r \ n vs \ n in the python eval function

Why does the eval function not work with \ r \ n, but with \ n. e.g. eval ("for me in range (5): \ r \ n print 'hello'") does not work eval ("for me in range (5): \ r \ n print 'hello" ") works

I know that the replacement problem ("\ r", "") does not cause problems, but does anyone know why this is happening?

- Edit-- Oh! Sorry, exactly, I meant exec. The carriage return appeared because I was reading the HTML text area through POST (I am in the Linux box). Now it’s clear, thanks to everyone.

+4
source share
2 answers

You have a strange definition of "work":

>>> eval("for i in range(5):\n print 'hello'") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 for i in range(5): ^ SyntaxError: invalid syntax >>> 

I'm not sure why you are using eval - I suspect you mean exec . Expressions and statements are essentially different objects in Python - eval processes only expressions (a simple expression is also an expression, so exec can deal with it, as well as with other operators).

Turning to exec and thinking of the situation as an explicit Python committer, I think this is a minor wrong design: just like (redundant and useless) spaces, tabs and form feeds before NEWLINE is accepted and ignored, so it should (like redundant and useless ) carriage return. I apologize: I think we never thought that someone might want to return the carriage there, but then it makes no sense to have, for example, forms, and we accept this ... therefore I see no reason to reject carriage returns ( or another Unicode space without ANSI), or now that in Python 3 we accept arbitrary Unicode characters other than ANSI in identifiers).

If you do not care, please open a problem with the tracker on the Python problem and (prohibit unforeseen opposition by other participants). I think I can fix it with Python 3.2 (which should be in 12-18 months) that the assessment is [informed assumption] and not a promise; -).

+6
source

Do you mean eval or exec? Please post exactly what you ran, plus a complete trace and error message.

The problem is probably because the Python grammar says that lines end with newline characters ('\ n'), rather than the two-character sequence '\ r \ n'.

In general, it would be safer to use replace ('\ r \ n', '\ n') if there is a meaningful β€œ\ r” somewhere. It would be better if you didn’t have "\ r" there in the first place ... how do you get the text - binary reading in a Windows window?

Speaking of security, you should be careful with using eval or exec on any old code received from a possible adversary.

+1
source

All Articles