How can I concatenate two integers in Python?
Asked Answered
F

18

47

How do I concatenate two integer numbers in Python? For example, given 10 and 20, I'd like a returned value of 1020.

Feigin answered 11/10, 2012 at 11:32 Comment(0)
H
6

The best way to do this in python was given in the accepted answer - but if you want to do this in jinja2 templates - the concatenation operator ~ gives you a neat way of doing this since it looks for the unicode representation of all objects, thus, you can 'concatenate integers' as well.

That is you can do this (given a=10 and b=20):

{{ a ~ b }}
Hifalutin answered 23/12, 2013 at 0:3 Comment(0)
E
71

Cast both to a string, concatenate the strings and then cast the result back to an integer:

z = int(str(x) + str(y))
Evangelical answered 11/10, 2012 at 11:33 Comment(0)
D
19

Using math is probably faster than solutions that convert to str and back:

If you can assume a two digit second number:

def f(x, y):
    return x*100+y

Usage:

>>> f(1,2)
102
>>> f(10,20)
1020

Although, you probably would want some checks included to verify the second number is not more than two digits. Or, if your second number can be any number of digits, you could do something like this:

import math
def f(x, y):
    if y != 0:
        a = math.floor(math.log10(y))
    else:
        a = -1

    return int(x*10**(1+a)+y)

Usage:

>>> f(10,20)
1020
>>> f(99,193)
99193

This version however, does not allow you to merge numbers like 03 and 02 to get 0302. For that you would need to either add arguments to specify the number of digits in each integer, or use strings.

Daleth answered 11/10, 2012 at 11:40 Comment(9)
don't you think importing math would slow things down?Sabrasabre
@gokcehan Yes, but if you were to call this function many times in a loop then the time to import math would be insignificantDaleth
Also, it makes more sense mathematically than string manipulation.Economize
Why not use ceil instead of using floor and adding one?Odometer
@Odometer ceil(num) != floor(num) + 1 for all num. Specifically, if num is an integer, then ceil(num) == floor(num). If you replaced floor()+1 with ceil() the function would not work properly when the second argument was an integer power of 10. (Since log10(10^n) = n you are in a case where floor(n) == ceil(n))Daleth
Yeah, I remember. Thanks.Odometer
This is not the problem requested. for example, it would not work if you try to concatenate 10 and 200, it would result in 1200 instead of 10200. you could use def f(x, y): return x*10**len(str(y))+y but I still think this isn't the point, as it seems the requester expected a string in output. it's a common problem in python to not be able to concatenate number.Zamboanga
@Zamboanga The OP requested to merge "two integer numbers", which at the time I interpreted to mean "two numbers of two digits each". This may not be what was intended, but I feel that the OP should have brought up the misunderstanding sooner, if this was not what was desired. This approach can be easily expanded to work more generally, if you have additional information about the numbers. Finally, strings containing numbers are not numbers. If strings were required/desired, it should have been stated.Daleth
Using Math converter is faster than converting to string and back in my testing: ``` In [28]: fn = lambda x, y: x*100 + y In [29]: timeit fn(1,2) 88.4 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [30]: timeit int(str(1) + str(2)) 427 ns ± 11.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) ```Schulein
L
17

Example 1: (Example 2 is much faster, don't say I didn't warn you!)

a = 9
b = 8
def concat(a, b):
    return eval(f"{a}{b}")

Example:

>>> concat(a, b)
98

Example 2:

For people who think eval is 'evil', here's another way to do it:

a = 6
b = 7
def concat(a, b):
    return int(f"{a}{b}")

Example:

>>> concat(a, b)
67

EDIT:

I thought it would be convienient to time these codes, look below:

>>> min(timeit.repeat("for x in range(100): int(str(a) + str(b))", "",
          number=100000, globals = {'a': 10, 'b': 20}))
9.107237317533617
>>> min(timeit.repeat("for x in range(100): int(f'{a}{b}')", "",
          number=100000, globals = {'a': 10, 'b': 20}))
6.4986298607643675
>>> min(timeit.repeat("for x in range(5): eval(f'{a}{b}')", "", #notice the range(5) instead of the range(100)
          number=100000, globals = {'a': 10, 'b': 20}))
4.089137231865948 #x20

The times:

eval: about 1 minute and 21 seconds.

original answer: about 9 seconds.

my answer: about 6 and a half seconds.

Conclusion:

The original answer does look more readable, but if you need a good speed, choose int(f'{vara}{varb}')

P.S: My int(f'{a}{b}) syntax only works on python 3.6+, as the f'' syntax is undefined at python versions 3.6-

Lovely answered 5/6, 2018 at 12:27 Comment(0)
H
6

The best way to do this in python was given in the accepted answer - but if you want to do this in jinja2 templates - the concatenation operator ~ gives you a neat way of doing this since it looks for the unicode representation of all objects, thus, you can 'concatenate integers' as well.

That is you can do this (given a=10 and b=20):

{{ a ~ b }}
Hifalutin answered 23/12, 2013 at 0:3 Comment(0)
A
5

using old-style string formatting:

>>> x = 10
>>> y = 20
>>> z = int('%d%d' % (x, y))
>>> print z
1020
Ardin answered 11/10, 2012 at 11:38 Comment(0)
C
4

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.

Chagall answered 11/10, 2012 at 11:37 Comment(0)
R
4

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
Rosalia answered 11/10, 2012 at 11:43 Comment(1)
Won't work concatenating 0 likelastnum=3 as numcat(lastnum,0) ValueError: math domain errorArbe
T
2

Just to give another solution:

def concat_ints(a, b):
    return a*(10**len(str(b)))+b

>>> concat_ints(10, 20)
1020
Tenenbaum answered 11/10, 2012 at 11:41 Comment(0)
P
2

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.

Political answered 11/10, 2012 at 11:50 Comment(1)
or just do: concat = lambda *args: int("".join(map(str, args))), it is faster :)Burin
D
2

Here's another way of doing it:

a = 10
b = 20

x = int('{}{}'.format(a, b))
Divisive answered 19/9, 2018 at 22:54 Comment(1)
Thats the best way for my opinionExcitement
A
2

To concatenate a list of integers

int(''.join(map(str, my_list)))
Animalist answered 10/1, 2020 at 9:54 Comment(0)
S
2

Using Math converter is faster than converting to string and back in my testing:

In [28]: fn = lambda x, y: x*10 + y                                                                               

In [29]: timeit fn(1,2)                                                                                            
88.4 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [30]: timeit int(str(1) + str(2))                                                                               
427 ns ± 11.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Schulein answered 14/8, 2020 at 22:59 Comment(3)
int(str(1) + str(2)) == fn(1,2) => FalseHamby
@Hamby I think I had an extra zero in there. I meant x*10 not x*100. Corrected it. My response was to a previous comment about speed of execution. In my observation it is slower going to string and back. Hope that helps!Schulein
I agree. For me this is the best way to concat two int.Hamby
F
1

A nice way as well would be to use the built-in reduce() function:

reduce(lambda x,y:x*10+y,[10,20])
Fiction answered 1/12, 2017 at 17:27 Comment(0)
N
1

I thought I would add a generalized formula for any number of digits:

import math
from functools import reduce


def f(*args):
    def numcat(a, b):
        return int(math.pow(10, (round(math.log(b, 10)) + 1)) * a + b)
    return reduce(numcat, args)


c = f(10, 1, 2, 1000, 3)  # 101210003
Nightstick answered 9/9, 2022 at 11:5 Comment(0)
P
0

You can simply cast both the integer values to string, add them and convert them again into integer:

x, y = str(10), str(20)

z = int(x + y)
Prickly answered 9/9, 2022 at 11:25 Comment(0)
C
0

Try print(f"{10}" + f"{20}") It should work!!

Coparcenary answered 26/12, 2022 at 13:6 Comment(0)
R
0

Taking 2 variable inputs you can do:

value1 = 10
value2 = 20
concatenated = int(f"{value1}{value2}")
print(concatenated)
Rein answered 30/1 at 13:38 Comment(1)
This seems to duplicate what at least two other answers have already suggested (the only difference is you're using different syntax).Eckstein
J
-1
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
Jentoft answered 24/6, 2014 at 19:41 Comment(2)
It would be good if you also would write some explaination to your code.Challah
Hmm. -1: your concatenate_int function look suspiciously like @Daleth 's answer.Lovely

© 2022 - 2024 — McMap. All rights reserved.