简体   繁体   中英

is there a way to do range() with ast.literal_eval?

or another way to ask I suppose is there a literal which will literal_eval to the equivalent of the range function (without sending the entire array as a range).

the following

import ast
ast.literal_eval("range(0,3)")
ast.literal_eval("[0, 1, 2, 3][0:3]")

results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/lib64/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

while this is possible it converts the entire array to a string then back which is not ideal. I was hoping for something with [0:3] syntax without the initial list.

>>> ast.literal_eval(str(range(0,3)))
[0, 1, 2]

http://docs.python.org/library/ast.html#ast.literal_eval

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

A range (other than an explicitly specified list) is not any of those, so no.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM