How to convert strings into integers in Python?

后端 未结 15 1906
自闭症患者
自闭症患者 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.

    0 讨论(0)
  • 2020-11-22 01:34

    In Python 3.5.1 things like these work:

    c = input('Enter number:')
    print (int(float(c)))
    print (round(float(c)))
    

    and

    Enter number:  4.7
    4
    5
    

    George.

    0 讨论(0)
  • 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:'
    
    0 讨论(0)
  • 2020-11-22 01:38

    Instead of putting int( ), put float( ) which will let you use decimals along with integers.

    0 讨论(0)
  • 2020-11-22 01:39

    Using list comprehensions:

    t2 = [map(int, list(l)) for l in t1]
    
    0 讨论(0)
  • 2020-11-22 01:40

    I would rather prefer using only comprehension lists:

    [[int(y) for y in x] for x in T1]
    
    0 讨论(0)
提交回复
热议问题