Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating values in a print statement [duplicate]

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.

like image 945
Auden Young Avatar asked Sep 09 '16 20:09

Auden Young


5 Answers

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
like image 198
linusg Avatar answered Oct 20 '22 03:10

linusg


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.

like image 41
Andrew Li Avatar answered Oct 20 '22 01:10

Andrew Li


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)
like image 38
rafaelc Avatar answered Oct 20 '22 01:10

rafaelc


print("Hello" + ' ' + name)

should do it on python 2

like image 1
A.. Avatar answered Oct 20 '22 03:10

A..


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)
like image 1
Mark Ransom Avatar answered Oct 20 '22 03:10

Mark Ransom