python – Concatenating values in a print statement

python – Concatenating values in a print statement

There are several ways to archive this:

Python 2:

>>> name = Bob
>>> print(Hello, name)
Hello Bob
>>> print(Hello %s % name)
Hello Bob

Python 3:

>>> name = Bob
>>> print(Hello {0}.format(name))
Hello Bob

Both:

>>> name = Bob
>>> print(Hello  + name)
Hello Bob

The reason why its printing unexpectedly is because in Python 2.x, print is a statement, not function, and the parentheses and space are creating a tuple. Print can take parentheses like in Python 3.x, but the problem is the space between the statement and parentheses. The space makes Python interpret it as a tuple. Try the following:

print Hello , name

Notice the missing parentheses. print isnt a function thats called, its a statement. It prints Hello Bob because the first string is and the variable separated by the comma is appended or concatenated to the string that is then printed. There are many other ways to do this in Python 2.x.

python – Concatenating values in a print statement

In Python 2.x, you can print out directly

print Hello, name

But you can also format your string

print (Hello %s % name)
print Hello {0}.format(name)

Leave a Reply

Your email address will not be published. Required fields are marked *