如何在Python print语句中让逗号、句号紧邻变量消除多余空格
问题原因
Python内置print()函数传递多个逗号分隔的参数时,默认会使用空格作为参数之间的分隔符(对应函数默认参数sep=' '),因此你代码里将标点作为单独参数传递时,就会在标点前后自动多出多余空格。
推荐解决方法
方法1:使用f-string格式化字符串(Python 3.6及以上版本推荐)
这是目前可读性最高、写法最简洁的方案,直接将变量嵌入字符串模板中,标点位置可以手动完全控制:
# 两个逻辑完全一致的分支可以合并减少重复代码 if year < 2001 or year > 2100: print(f"{name}, you were born in {year}.") else: print(f"{name}, you were born in {year}, which is the 21st century.") print(f"{name}'s classification is {classification}.")
注:你原代码中year<2001和year>2100两个分支逻辑完全一致,已合并为同一个判断条件
方法2:使用str.format() 兼容旧版本Python
如果需要兼容Python3.5及更早版本,可以用format方法实现同样的格式化效果:
if year < 2001 or year > 2100: print("{}, you were born in {}.".format(name, year)) else: print("{}, you were born in {}, which is the 21st century.".format(name, year)) print("{}'s classification is {}.".format(name, classification))
方法3:修改print函数的sep参数
如果你不想调整字符串拼接逻辑,可以直接把分隔符参数sep设置为空字符串,手动在需要空格的位置补空格:
if year < 2001 or year > 2100: print(name, ", you were born in ", year, ".", sep='') else: print(name, ", you were born in ", year, ", which is the 21st century.", sep='') print(name, "'s classification is ", classification, ".", sep='')
内容的提问来源于stack exchange,提问作者amanda
相关产品推荐
相关产品推荐

