Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

parsing - Python "safe" eval (string to bool/int/float/None/string)

I'm making a webapp that does some data processing, so I frequently find myself parsing strings (from an URL or a text file) into Python values.

I use a function that is "kind of" a safer version of eval (except that if it can't read the string, it stays a string):

def str_to_value(string):
    for atom in (True, False, None):
        if str(atom) == string:
            return atom
    else:
        try:
            return int(string)
        except ValueError:
            try:
                return float(string)
            except ValueError:
                return string

... however, this seems very ugly to me. Is there a cleaner way of doing this? I found an old discussion os something like this, but I'm wondering if there isn't a quick and simple way (like a library function I don't know of, or a clever one-liner?).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ast.literal_eval()

>>> ast.literal_eval('{False: (1, 0x2), True: [3.14, 04, 0b101], None: ("6", u"7", r'8')}')
{False: (1, 2), True: [3.1400000000000001, 4, 5], None: ('6', u'7', '8')}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...