Reputation: 911
My code looks like this:
name = Joe
print "Hello", name, "!"
My output looks like:
Hello Joe !
How do I remove the space between Joe
and !
?
Upvotes: 2
Views: 39366
Reputation: 347
There are several ways of constructing strings in python. My favorite used to be the format function:
print "Hello {}!".format(name)
You can also concatenate strings using the + operator.
print "Hello " + name + "!"
More information about the format function (and strings in general) can be found here: https://docs.python.org/2/library/string.html#string.Formatter.format
You can now use something called f-Strings
if you're using python 3.6 or newer. Just prefix the string with the letter f
then insert variable names inside some brackets.
print(f"Hello {name}")
Upvotes: 11
Reputation: 1001
>>> print (name)
Joe
>>> print('Hello ', name, '!')
Hello Joe !
>>> print('Hello ', name, '!', sep='')
Hello Joe!
Upvotes: 2
Reputation: 355
One other solution would be to use the following:
Print 'Hello {} !'.format(name.trim())
This removes all the leading and trailing spaces and special character.
Upvotes: 1
Reputation: 42007
You can also use printf
style formatting:
>>> name = 'Joe'
>>> print 'Hello %s !' % name
Hello Joe !
Upvotes: 1
Reputation: 36662
a comma after print will add a blank space.
What you need to do is concatenate the string you want to print; this can be done like this:
name = 'Joe'
print 'Hello ' + name + '!'
Joe
must be put between quotes
to define it as a string.
Upvotes: 2