Reputation: 10686
Is there a way to concat numbers in Python, lets say I have the 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?
Upvotes: 4
Views: 18971
Reputation: 411
print(f'{2}{1}')
gives
21
[Program finished]
The format used by OP.
It's <class 'str'>
Upvotes: 0
Reputation: 1
If we do not want to convert it into a string.
val = [1,2,3,4] reduce(lambda x,y: x*10+y, val)
or after getting the result. convert it back to Integer.
Upvotes: 0
Reputation: 10732
Use the string formatting operator:
print "%d%d" % (2, 1)
EDIT: In Python 2.6+, you can also use the format() method of a string:
print("{0}{1}".format(2, 1))
Upvotes: 10
Reputation: 29302
If you have a lot of digits use str.join()
+ map()
:
print(''.join(map(str, [2,1])))
Otherwise why not simply do:
print(2*10+1)
Upvotes: 6
Reputation: 5622
You can change the separator used by the print function:
print(2, 1, sep="")
If you're using python2.x, you can use
from __future__ import print_function
at the top of the file.
Upvotes: 8
Reputation: 24153
>>> import sys
>>> values = [1, 2, 3, 4, 5]
>>> for value in values:
sys.stdout.write(str(value))
12345
Upvotes: 2
Reputation: 1021
If you use python 3.x or 2.7, use format
print("{0}{1}".format(2, 1))
Upvotes: 3
Reputation: 2373
You could perhaps convert the integers to strings:
print(str(2)+str(1))
Upvotes: 10
Reputation: 91132
This is because 2 and 1 are integers, not strings. In general if you want to do this in any context besides printing, you'd have to convert them to strings first. For example:
myNumber1 = ...
myNumber2 = ...
myCombinedNumberString = str(myNumber1)+str(myNumber2)
In the context of printing, you'd much rather do what Rafael suggests in his answers (string format operator). I'd personally do it like:
print( '{}{}'.format(2,1) )
Upvotes: 5