Home > Back-end >  New line and whitespace at the end of a string
New line and whitespace at the end of a string

Time:01-21

Task

Write multiple if statements:

  • If car_year is 1969 or earlier, print "Few safety features."
  • If 1970 or later, print "Probably has seat belts."
  • If 1990 or later, print "Probably has antilock brakes."
  • If 2000 or later, print "Probably has airbags."

End each phrase with a period and a newline.

Sample output

For input: 1995

Probably has seat belts.
Probably has antilock brakes.

Code

car_year = int(input())

if car_year <=1969:
    message='Few safety features'
    print(message '.''\n')
if car_year >=1970:
    message1='Probably has seat belts'
    print(message1 '.''\n')
if car_year >=1990:
    message2='Probably has antilock brakes'
    print(message2 '.''\n')
if car_year >=2000:
    message3='Probably has airbags'
    print(message3 '.''\n')

Problem

This is what I was getting originally:

  • two new-lines after the sentence (2nd highlighted in the image)

two new-lines after the sentence

After trying a few solutions I keep getting this:

  • a space after the sentence (highlighted in the image)

a space after the sentence

Sorry for the terrible explanation. I'm new to coding and don't know how to explain exactly what I'm thinking.

CodePudding user response:

You are adding a newline (\n) to the string, but print automatically adds a single newline after the string, so you get two newlines in total. Just remove the \ns to get a single newline (the one automatically added by print).

CodePudding user response:

You can use the end attribute of the print function for this

car_year = int(input())

if car_year <=1969:
    message='Few safety features'
    print(message '.', end=" ")
if car_year >=1970:
    message1='Probably has seat belts'
    print(message1 '.', end="")
if car_year >=1990:
    message2='Probably has antilock brakes'
    print(message2 '.', end=" ")
if car_year >=2000:
    message3='Probably has airbags'
    print(message3 '.', end=" ")
  •  Tags:  
  • Related