How to convert strings into integers in Python?

后端 未结 15 2232
自闭症患者
自闭症患者 2020-11-22 01:33

I have a tuple of tuples from a MySQL query like this:

T1 = ((\'13\', \'17\', \'18\', \'21\', \'32\'),
      (\'07\', \'11\', \'13\', \'14\', \'28\'),
               


        
15条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:34

    See this function

    def parse_int(s):
        try:
            res = int(eval(str(s)))
            if type(res) == int:
                return res
        except:
            return
    

    Then

    val = parse_int('10')  # Return 10
    val = parse_int('0')  # Return 0
    val = parse_int('10.5')  # Return 10
    val = parse_int('0.0')  # Return 0
    val = parse_int('Ten')  # Return None
    

    You can also check

    if val == None:  # True if input value can not be converted
        pass  # Note: Don't use 'if not val:'
    

提交回复
热议问题