You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python print打印时间字符串末尾加.出现多余空格如何解决

问题原因

你遇到的多余空格是Python print() 函数的默认机制导致的:当你传入多个用逗号分隔的参数时,print() 会自动在参数之间插入空格,所以你把句号作为单独参数传入时,就会和前面的时间内容之间多出不必要的空格。


解决方案

方案1:使用f-string(推荐,Python 3.6及以上版本支持)

这是最简洁易读的写法,直接把变量嵌入字符串模板中,不会产生多余空格:

import datetime
# 自动获取当前日期时间输出
now = datetime.datetime.now()
print(f"[Today is {now.strftime('%Y-%m-%d')} and it is {now.strftime('%H:%M:%S')}.]")

# 如需手动指定日期时间,写法如下
print(f"[Today is {datetime.date(2021,9,3)} and it is {datetime.time(9,31,35)}.]")

方案2:使用datetime的strftime方法直接格式化

可以一步生成符合要求的字符串,无需单独拼接日期和时间对象:

import datetime
now = datetime.datetime.now()
# 直接按目标格式输出,包含外侧方括号和末尾句号
print(now.strftime("[Today is %Y-%m-%d and it is %H:%M:%S.]"))

方案3:兼容旧版本Python的str.format()写法

如果使用Python 3.5及更早版本,不支持f-string,可以用format方法实现同样效果:

import datetime
print("[Today is {} and it is {}.]".format(datetime.date(2021,9,3), datetime.time(9,31,35)))

内容的提问来源于stack exchange,提问作者user16826661

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:30:03