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.
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 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.
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)
print("Hello" + ' ' + name)
should do it on python 2
You are seeing the difference between Python 2 and Python 3. In Python 2, the print
is a statement and doesn't need parentheses. By adding parentheses you end up creating a tuple, which doesn't print the way you want. Simply take out the parentheses.
print "Hello", name
Often you won't see this effect because you're only printing one item; putting parentheses around a single item doesn't create a tuple. The following would work the same in Python 2 and Python 3:
print(name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With