heather heather - 1 year ago 71
Python Question

Removing the parentheses and comma in print statement result

Let's say I have the code

name = "Bob"
print ("Hello", name)

This gives

('Hello', 'Bob')

Which I don't want.
If I put in the code

name = "Bob"
print "Hello"
print name

This gives


Which is also not what I want. I just want plain old

Hello Bob

How do I get that? I apologize in advance if this is a duplicate or dumb question.

Answer Source

The reason why it's 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 isn't a function that's called, it's 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.