Reputation: 13
I have just started out with Python, and am using Idle.
I put in:
print("Professor Redwood: Right! So your name is",name,"!")
And got this in the console:
Professor Redwood: Right! So your name is Chase !
Notice the spaces around the name "Chase"
. I can't figure out how to get rid of these spaces. I looked up this question, and went to this page. I could not understand what the answer meant, so I need some help with it.
(Please note that I have already set the variable.)
Upvotes: 0
Views: 120
Reputation: 160367
By default, the Python print
function uses a separation set to a single space when printing arguments; you can easily override this by defining sep=''
(i.e empty space):
print("Professor Redwood: Right! So your name is",name,"!", sep='')
Which will now print
:
Professor Redwood: Right! So your name isChase!
For Python 2.x
you could either use from __future__ import print_function
and if that doesn't suit you for some undisclosed reason, use join
to explicitly join on the empty string:
print "".join(["Professor Redwood: Right! So your name is",name,"!"])
or, use .format
as the other answer suggests:
print "Professor Redwood: Right! So your name is{0}!".format(name)
Upvotes: 4
Reputation: 91525
What you're trying to do is concatenate strings which isn't exactly what commas in the print
statement do. Instead, concatenation can be achieved several ways, the most common of which is to use the +
operator.
print("Professor Redwood: Right! So your name is " + name + "!")
or you can concatenate into a variable and print that. This is especially useful if you're concatenating lots of different strings or you want to reuse the string several times.
sentence = "Professor Redwood: Right! So your name is " + name + "!"
print sentence
or you can use string formatting. This has the benefit of usually looking cleaner and allowing special variable types such as decimals or currency to be formatted correctly.
print "Professor Redwood: Right! So your name is %s!" % name
print "Professor %s: Right! So your name is %s!" % (prof_name, name)
print "Professor Redwood: Right! So your name is {0}!".format(name)
Note that in Python 2, the print statement does not require brackets around the string. In Python 3 they are required.
Upvotes: 1
Reputation: 7100
Another option using string concatenation:
print("Professor Redwood: Right! So your name is"+ name + "!")
You could also do the following using string formatting
print("Professor Redwood: Right! So your name is {0} !".format(name))
Upvotes: 3