How do you concatenate numbers in python?

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-

Introduction

Python supports string concatenation using the + operator. In most other programming languages, if we concatenate a string with an integer (or any other primitive data types), the language takes care of converting them to a string and then concatenates it.

However, in Python, if you try to concatenate a string with an integer using the + operator, you will get a runtime error.

Example

Let’s look at an example for concatenating a string (str) and an integer (int) using the + operator.

string_concat_int.py

current_year_message = 'Year is '

current_year = 2018

print(current_year_message + current_year)

The desired output is the string: Year is 2018. However, when we run this code we get the following runtime error:

Traceback (most recent call last):
  File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
    print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str

So how do you concatenate str and int in Python? There are various other ways to perform this operation.

Using the str() Function

We can pass an int to the str() function it will be converted to a str:

print(current_year_message + str(current_year))

The current_year integer is returned as a string: Year is 2018.

Using the % Interpolation Operator

We can pass values to a conversion specification with printf-style String Formatting:

print("%s%s" % (current_year_message, current_year))

The current_year integer is interpolated to a string: Year is 2018.

Using the str.format() function

We can also use the str.format() function for concatenation of string and integer.

print("{}{}".format(current_year_message, current_year))

The current_year integer is type coerced to a string: Year is 2018.

Using f-strings

If you are using Python 3.6 or higher versions, you can use f-strings, too.

print(f'{current_year_message}{current_year}')

The current_year integer is interpolated to a string: Year is 2018.

Conclusion

You can check out the complete Python script and more Python examples from our GitHub repository.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given two integers a and b. The task is to concatenate these two integers into one integer.

    Examples:

    Input : a = 806, b = 91
    Output : 80691
    
    Input : a = 5, b = 1091
    Output : 51091
    
    

    Method 1: One method of achieving this can be counting the number of digits of second number. Then multiply the first number with 10^digits and adding both the numbers. Below is the implementation.

    def numConcat(num1, num2):

         digits = len(str(num2))

         num1 = num1 * (10**digits)

         num1 += num2

         return num1

    a = 906

    b = 91

    print(numConcat(a, b))

    Method 2: Another method can be converting both the numbers to the string. Then concatenate them and convert them back to integers. Below is the implementation.

    def numConcat(num1, num2):

            num1 = str(num1)

            num2 = str(num2)

            num1 += num2

            return int(num1)

    a = 906

    b = 91

    print(numConcat(a, b))

    Output:

    90691
    

    How do you concatenate a list of numbers in Python?

    Python concatenate lists without duplicates To concatenate the list without duplicates I have used set(list2) – set(list1) to find the difference between the two lists. The list and the new list are concatenated by using the “+” operator. The print(list) is used to get the output.

    How do you concatenate numbers?

    To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator.

    How do you concatenate a number in a string in Python?

    Python Concatenate String and Int.
    Using the str() Function. We can pass an int to the str() function it will be converted to a str : ... .
    Using the % Interpolation Operator. We can pass values to a conversion specification with printf-style String Formatting: ... .
    Using the str. format() function..

    How do you concatenate elements in Python?

    Using join() method to concatenate items in a list to a single string. The join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.