Printing concatenation of digits of two numbers in Python

Is there a way to concat number in Python, say I have code

print(2, 1) 

I want it to print 21 , not 2 1 , and if I use +, it prints 3. Is there a way to do this?

+4
source share
9 answers

Perhaps you can convert integers to strings:

 print(str(2)+str(1)) 
+8
source

Use the string formatting operator:

 print "%d%d" % (2, 1) 

EDIT: in Python 2.6+, you can also use the format () method for the string:

 print("{0}{1}".format(2, 1)) 
+9
source

You can change the separator used by the print function:

 print(2, 1, sep="") 

If you are using python2.x you can use

 from __future__ import print_function 

at the top of the file.

+8
source

If you have a lot of numbers, use str.join() + map() :

 print(''.join(map(str, [2,1]))) 

Otherwise, why not just do:

 print(2*10+1) 
+6
source

This is because 2 and 1 are integers, not strings. In general, if you want to do this in any context other than printing, you will first have to convert them to strings. For instance:

 myNumber1 = ... myNumber2 = ... myCombinedNumberString = str(myNumber1)+str(myNumber2) 

In the print context, you'd rather do what Rafael offers in his answers (string formatting operator). I personally would do it like this:

 print( '{}{}'.format(2,1) ) 
+5
source

If you are using python 3.x or 2.7, use format

 print("{0}{1}".format(2, 1)) 
+3
source
 >>> import sys >>> values = [1, 2, 3, 4, 5] >>> for value in values: sys.stdout.write(str(value)) 12345 
+2
source

If we do not want to convert it to a string.

val = [1,2,3,4] decrease (lambda x, y: x * 10 + y, val)

or after receiving the result. convert it back to Integer.

0
source

Just use

 c="2"+"1" print(c) 

He will give you 21 .

-one
source

Source: https://habr.com/ru/post/1398692/


All Articles