How do I concatenate two integer numbers (for example: 10 and 20) in Python to get a returned value of 1020?
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-