且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python eval函数中的\ r \ n与\ n

更新时间:2022-10-25 12:53:07

您对工作"有一个奇怪的定义:

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

我不确定您为什么使用eval-我怀疑您的意思是exec.表达式和语句在Python中是完全不同的实体-eval仅处理表达式(裸表达式也是也是一条语句,因此exec可以处理它以及其他语句). /p>

转到exec,并考虑作为Python核心提交者的情况,我认为这是一个小错误的设计:就像(冗余和无用的)空格,制表符和换页符一样,在接受和忽略NEWLINE之前,因此(应该是多余和无用的)回车也应该如此.我深表歉意:我认为我们从未考虑过有人可能会想要在这里放回车票-但是,那么,例如在那里,我们确实接受那个 ...,所以我也没有拒绝拒绝回车符的理由(或者其他Unicode非ANSI空格,现在在Python 3中我们接受任意的Unicode非-)也无济于事..............................................................................................它们一起

如果您愿意的话,请在Python的问题跟踪器上打开一个问题,并且(除非其他提交者出现不可预见的反对),我认为我可以通过Python 3.2来解决此问题(应该在12到18个月内解决,这是一个估计值) [有根据的猜测],不是承诺;-).

Why eval function doesn't work with \r\n but with \n. for example eval("for i in range(5):\r\n print 'hello'") doesn't work eval("for i in range(5):\n print 'hello'") works

I know there is not a problem cause using replace("\r","") is corrected, but someone knows why happens?

--Edit-- Oh! sorry , exactly, I meant exec. Carriage returns appeared because I'm reading from a HTML textarea via POST (I'm on a Linux box). now It is clearer, thanks to everyone.

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're using eval -- I suspect you mean exec. Expressions and statements are drastically different entities in Python -- eval only deals with expressions (a bare expression is also a statement, so exec can deal with it as well as other statements).

Turning to exec, and pondering the situation as a Python core committer, I think it's a minor mis-design: just like (redundant and useless) spaces, tabs and form feeds just before a NEWLINE are accepted and ignored, so should (just as redundant and useless) carriage returns be. I apologize: I think we never ever considered that somebody might want to put carriage returns there -- but then, it doesn't make any more sense to have e.g. form feeds there, and we do accept that... so I see no rationale for rejecting carriage returns (or other Unicode non-ANSI whitespace, either, now that in Python 3 we accept arbitrary Unicode non-ANSI alphanumerics in identifiers).

If you care, please open an issue on Python's issue tracker, and (barring unforeseen opposition by other commiters) I think I can get it fixed by Python 3.2 (which should be out in 12 to 18 months -- that's an estimate [informed guess], not a promise;-).