4

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,'!')

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

5 Answers5

5

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 + '!')
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
4

in python 3.6 you could use fstrings which are well readable and slightly faster than the other format-methods :

print(f'Hello {fn} {ln}!')
4

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!
>>>
WombatPM
  • 2,561
  • 2
  • 22
  • 22
2

This is a job for format strings.

Python 3:

print('Hello {} {}!'.format(fn, ln))

Python 2:

print 'Hello %s %s!' % (fn, ln)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

You can take the element before the exclamation mark (ln) and concatenate the '!' on to the end:

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

giving:

Hello, Fist Last!

The print() statement documentation states that:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep

and since by default, sep is a space (' '), you get spaces between each of the arguments you passed into the function. As above, if you concatenate the exclamation mark onto ln yourself, the default sep parameter is not inserted and you will not get a space.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54