How to convert strings into integers in Python?

后端 未结 15 2125
自闭症患者
自闭症患者 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:33

    Try this.

    x = "1"
    

    x is a string because it has quotes around it, but it has a number in it.

    x = int(x)
    

    Since x has the number 1 in it, I can turn it in to a integer.

    To see if a string is a number, you can do this.

    def is_number(var):
        try:
            if var == int(var):
                return True
        except Exception:
            return False
    
    x = "1"
    
    y = "test"
    
    x_test = is_number(x)
    
    print(x_test)
    

    It should print to IDLE True because x is a number.

    y_test = is_number(y)
    
    print(y_test)
    

    It should print to IDLE False because y in not a number.

提交回复
热议问题