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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...