Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not print a space after a comma [duplicate]

Tags:

python

output

This is my current code. The print will put a space prior to the "!" and I've searched the forums for an hour, but everything is way too complicated for me right now. It's a stupid question, but I have to know why it's adding this random space after a comma.

fn = input("What's your First Name? ")
ln = input("What's your Last Name? ")
print ('Hello,',fn, ln,'!')

like image 206
Yanni Asimacopoulos Avatar asked Dec 10 '22 09:12

Yanni Asimacopoulos


2 Answers

It's a stupid question, but I have to know why it's adding this random space after a comma.

The default setting of print is such that comma adds whitespace after it.

One way of removing the space before ! here is doing :

print('Hello,',fn, ln, end='')
print('!')

Out : Hello, First Last!

Here the end= specifies what should be printed upon end of print() statement instead of the default newline.

Another far more easier method is just to concatenate the string. ie,

print('Hello,',fn, ln + '!')
like image 88
Kaushik NP Avatar answered Dec 20 '22 21:12

Kaushik NP


When you print a list of strings python inserts a space.

$ python3
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 08:49:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('My','name','is','doug')
My name is doug
>>> print('My'+'name'+'is'+'doug')
Mynameisdoug

You want to either combine you elements into a single string OR (the better way) use string formatting to output.

>>> fn = "Bob"
>>> ln = "Jones"
>>> msg = "Hello, "+fn+" "+ln+"!"
>>> print(msg)
Hello, Bob Jones!
>>> msg = "Hello, {0} {1}!".format(fn,ln)
>>> print(msg)
Hello, Bob Jones!
>>>
like image 28
WombatPM Avatar answered Dec 20 '22 20:12

WombatPM