PyCharm编写Python出生年份计算程序时print输出多余空格求解
问题原因
Python的print()函数默认接收多个逗号分隔的参数时,会在参数之间自动插入一个空格(对应函数默认参数sep=' ')。你的代码中把感叹号!、句号.都作为独立参数传入print,因此这两个符号前面会被自动加上多余空格。
另外你贴的代码中,user_name和user_age两行开头有多余的缩进,直接运行会触发缩进错误,需要删掉行首的多余空格。
修复方案
最简洁易读的修复方式是使用f-string把所有输出内容整合为单个字符串传入print,不需要拆分多个参数,从根源避免自动加空格的问题。
修正后的完整可运行代码:
from datetime import date # 接收用户输入 user_name = input('What is your name?') user_age = int(input('What is your age?')) current_yr = date.today().year # 计算出生年份 birth_year = current_yr - user_age # 输出结果 print(f'Hello {user_name}! You were born in {birth_year}.')
其他可选写法
如果你使用的Python版本低于3.6(不支持f-string语法),可以用以下两种等效写法:
- 使用字符串format方法:
print('Hello {}! You were born in {}.'.format(user_name, birth_year))
- 手动拼接需要连写的内容段,再传入print:
print('Hello', f'{user_name}!', 'You were born in', f'{birth_year}.')
修复后运行代码,输入名字John、对应年龄,就会输出符合预期的结果:Hello John! You were born in 1992.,不存在多余空格。
内容的提问来源于stack exchange,提问作者Kameron Green
相关产品推荐
相关产品推荐

