How do I concatenate two integer numbers (for example: 10 and 20) in Python to get a returned value of 1020?
To concatenate a list of integers
int(''.join(map(str, my_list)))
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
.
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
using old-style string formatting:
>>> x = 10
>>> y = 20
>>> z = int('%d%d' % (x, y))
>>> print z
1020
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
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.