简体   繁体   中英

How to check for a string's “natural” datatype in Python?

I have a user inputting arguments to the command line when running a python3 script, and I wish to check whether specific arguments are floats, ints, booleans, or strings. I'm familiar with the errors that are thrown when a string like 'car' is cast to an int using the int() function, and am also familiar with using a try/except block to attempt to cast a string to an int, and if this is unsuccessful, how to map error messages to helpful output to the user. I've also seen this previous question, which will probably do the job. Was just wondering if there had been any new development.

Not sure if this is possible, but looking for a smart type() function that could operate as such:

#!/usr/bin/env python3

import sys

smarttype(sys.argv[-1])

and is capable of handling the following kinds of inputs:

./script.py 50
./script.py True
./script.py 50.0
./script.py run

and output:

int
bool
float
str

I usually use ast.literal_eval to parse “elementary” data types:

type(ast.literal_eval('50')) # outputs int

You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string):

type(ast.literal_eval('run')) # error
type(ast.literal_eval('"run"')) # string

If you want to allow unqouted strings you could do the following:

def parse_data(x):
    """Takes a string x and returns the "value" of x"""
    try:
        return ast.literal_eval(x)
    except (ValueError, SyntaxError):
        return x

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