10

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.

jwpfox
  • 5,124
  • 11
  • 45
  • 42
Auden Young
  • 1,147
  • 2
  • 18
  • 39

6 Answers6

13

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
linusg
  • 6,289
  • 4
  • 28
  • 78
6

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.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
2

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)
rafaelc
  • 57,686
  • 15
  • 58
  • 82
1

Replace your comma (,) with a plus sign (+), and add some appropriate spacing.

Code

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

Output

Hello Bob
jwpfox
  • 5,124
  • 11
  • 45
  • 42
measure_theory
  • 874
  • 10
  • 28
1
print("Hello" + ' ' + name)

should do it on python 2

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
A..
  • 65
  • 8
1

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)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622