How to concatenate two integers in Python?

前端 未结 14 1906
南旧
南旧 2020-12-15 03:51

How do I concatenate two integer numbers (for example: 10 and 20) in Python to get a returned value of 1020?

相关标签:
14条回答
  • 2020-12-15 04:11

    To concatenate a list of integers

    int(''.join(map(str, my_list)))
    
    0 讨论(0)
  • 2020-12-15 04:15

    Using this function you can concatenate as many numbers as you want

    def concat(*args):
        string = ''
        for each in args:
            string += str(each) 
        return int(string)
    

    For example concat(20, 10, 30) will return 201030 an an integer

    OR

    You can use the one line program

    int(''.join(str(x) for x in (20,10,30)))
    

    This will also return 201030.

    0 讨论(0)
  • 2020-12-15 04:15
    def concatenate_int(x, y):
    
      try:
         a = floor(log10(y))
      except ValueError:
         a = 0
      return int(x * 10 ** (1 + a) + y)
    
    
    def concatenate(*l):
      j = 0
      for i in list(*l):
         j = concatenate_int(j, i)
      return j
    
    0 讨论(0)
  • 2020-12-15 04:16

    using old-style string formatting:

    >>> x = 10
    >>> y = 20
    >>> z = int('%d%d' % (x, y))
    >>> print z
    1020
    
    0 讨论(0)
  • 2020-12-15 04:17

    Of course the 'correct' answer would be Konstantin's answer. But if you still want to know how to do it without using string casts, just with math:

    import math
    
    def numcat(a,b):
        return int(math.pow(10,(int(math.log(b,10)) + 1)) * a + b)
    
    >> numcat(10, 20)
    >> 1020
    
    0 讨论(0)
  • 2020-12-15 04:19

    A rough but working implementation:

    i1,i2 = 10,20
    num = int('%i%i' % (i1,i2))
    

    Basically, you just merge two numbers into one string and then cast that back to int.

    0 讨论(0)
提交回复
热议问题