您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中将数字格式化为字符串

在Python中将数字格式化为字符串

从Python 3.6开始,可以使用格式化的字符串文字f-strings 完成Python中的格式化

hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'

str.format以2.7开头的函数

"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")

或甚至更旧版本的Python的字符串格式%运算符,但请参阅文档中的注释:

"%02d:%02d:%02d" % (hours, minutes, seconds)

对于您特定的格式化时间,有time.strftime

import time

t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%s %p', t)
python 2022/1/1 18:35:51 有216人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶