Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string and int in python 3.4 [duplicate]

Tags:

python

string

I'm new to Python, so I've been running through my own set of exercises to simply start memorizing basic functions and syntax.

I'm using the PyCharm IDE and Python 3.4. I've run into an issue when running through some basic string and integer concatenation exercises. Each instance below is throwing an unsupported operand type. There are several threads on Stack Overflow that clearly states proper concatenation syntax, but the above error message continues to plague me.

print ("Type string: ") + str(123)
print ("Concatenate strings and ints "), 10
like image 636
apt-get Avatar asked Nov 29 '22 14:11

apt-get


1 Answers

In Python 3+, print is a function, so it must be called with its arguments between parentheses. So looking at your example:

print ("Type string: ") + str(123)

It's actually the same as:

var = print("Type string: ")
var + str(123)

Since print returns nothing (in Python, this means None), this is the equivalent of:

None + str(123)

which evidently will give an error.

That being said about what you tried to do, what you want do to is very easy: pass the print function what you mean to print, which can be done in various ways:

print ("Type string: " + str(123))

# Using format method to generate a string with the desired contents
print ("Type string: {}".format(123)) 

# Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
print ("Type string:", str(123)) # Notice this will insert a space between the parameters
like image 197
Rafael Lerm Avatar answered Dec 05 '22 15:12

Rafael Lerm