Home > database >  PyCharm program for showing year of birth
PyCharm program for showing year of birth

Time:07-11

I am looking to write a program in python that would print "Hello" user_name ! "you were born in" birth_year "." I have the code that would produce this, but I am getting a space in the output and I can't figure out why/how to remove it.

Code is here: from datetime import date

# ask user for input here
 user_name = input('What is your name?')
 user_age = int(input('What is your age?'))
 current_yr = date.today().year

# calculation for birth year from user input
birth_year = (current_yr - user_age)

# print output from user
print('Hello', user_name, "!", 'You were born in', birth_year, ".")

That is my code there. I need the output to look like this :

Hello John! You were born in 1992.

I keep getting this instead: Hello John ! You were born in 1992 .

Any help would be appreciated.

CodePudding user response:

have you tried to use f-string:

print(f'Hello{user_name}! You were born in {birth_year}.')

CodePudding user response:

Print function in Python separates each argument with a space by default, so in

print('Hello', user_name, "!", 'You were born in', birth_year, ".")

everywhere where you have a coma, there will be a space in the resulting string. There are two approaches to solve this:

  • You can change the separator by adding additional sep='' argument (it'll make print separate arguments with nothing), but you'll have to manually add spaces where necessary:
print('Hello ', user_name, "!", ' You were born in ', birth_year, ".", sep='')
# or even shorter:
print('Hello ', user_name, '! You were born in ', birth_year, '.', sep='')
  • You can use formatted strings (as suggested by Toshio):
print(f'Hello{user_name}! You were born in {birth_year}.')
  • Related