我希望用python编写一个程序,可以打印"Hello"user_name !"你出生在……"birth_year"!"我的代码会产生,但我在输出空间,我琢磨不透为什么/如何删除它。
代码如下:从datetime导入日期
# 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, ".")
这是我的代码。我需要输出如下所示:
你好,约翰!你是1992年出生的。
我一直收到这个:你好,约翰!你是1992年出生的。
如有任何帮助,不胜感激。
您是否尝试使用f-string:
打印(f 'Hello {user_name} !你出生在{birth_year}年
Python中的Print函数默认使用空格分隔每个参数,因此在
中print('Hello', user_name, "!", 'You were born in', birth_year, ".")
在中有逗号的地方,结果字符串中会有一个空格。有两种方法可以解决这个问题:
- 你可以通过添加额外的
sep=''
参数来改变分隔符(它将使print
独立的参数没有任何内容),但是你必须在必要的地方手动添加空格:
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='')
- 你可以使用格式化字符串(由Toshio建议):
print(f'Hello{user_name}! You were born in {birth_year}.')