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

后端 未结 5 1195
感情败类
感情败类 2020-12-02 01:40

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.

5条回答
  •  半阙折子戏
    2020-12-02 02:30

    def int_float_none(x):
        # it may be already int or float 
        if isinstance(x, (int, float)):
            return x
        # all int like strings can be converted to float so int tries first 
        try:
            return int(x)
        except (TypeError, ValueError):
            pass
        try:
            return float(x)
        except (TypeError, ValueError):
            return None
    

    Function above for any object passed will return int or float conversion or None.

提交回复
热议问题