Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Space between variable and string in Python

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 !?

like image 284
TrentWoodbury Avatar asked Mar 25 '26 17:03

TrentWoodbury


2 Answers

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

6 Years Later...

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}")
like image 200
Ben Force Avatar answered Mar 28 '26 06:03

Ben Force


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.

like image 21
Reblochon Masque Avatar answered Mar 28 '26 07:03

Reblochon Masque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!