Search code examples
pythonpython-2.7outputstring-concatenation

Concatenating values in a print statement


I have the string "Bob" stored in a variable called name.

I want to print this:

Hello Bob

How do I get that?


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

Hello
Bob

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.


Solution

  • 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.