Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How can I convert a string to either int or float with priority on int?

I couldn't find another answer when I wanted this, so I thought I would post my own solution for anyone else and also get corrections if I've done something wrong.

I had to make an automatic config file parser and I preferred to make numbers int if possible and float if not. The usual try/except conversion doesn't work by itself since any float will just be coerced to an int.

To clarify as someone asked, the case is basically to convert numbers as the person writing the config file data intended them to be. So anything with decimals would probably be intended to be a float. Also, I believe that float can be dangerous for some operators (e.g. ==, <, >) due to the nature of floating point numbers, and int will be converted to float when necessary. Therefore I prefer numbers to stay in int when possible. Not a big thing, just as a kind of convention for myself.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
def int_or_float(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

If you want something like "10.0000" converted to int, try this:

def int_dammit_else_float(s):
    f = float(s)
    i = int(f)
    return i if i == f else f

What result do you want for input like "1e25"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...