在 Python 中将数字格式化为字符串 [英] Format numbers to strings in Python
问题描述
我需要了解如何将数字格式化为字符串.我的代码在这里:
I need to find out how to format numbers as strings. My code is here:
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
小时和分钟是整数,秒是浮点数.str() 函数会将所有这些数字转换为十分之一 (0.1) 的位置.因此,不是我的字符串输出5:30:59.07 pm",而是显示类似5.0:30.0:59.1 pm"的内容.
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".
最重要的是,我需要什么库/函数来为我做这件事?
Bottom line, what library / function do I need to do this for me?
推荐答案
从 Python 3.6 开始,可以使用 格式化字符串文字 或f-strings:
Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
或str.format
从 2.7 开始的函数:
or the str.format
function starting with 2.7:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
或字符串格式%
运算符适用于更旧版本的Python,但请参阅文档中的注释:
or the string formatting %
operator for even older versions of Python, but see the note in the docs:
"%02d:%02d:%02d" % (hours, minutes, seconds)
对于格式化时间的具体情况,有 time.strftime
:
And for your specific case of formatting time, there’s time.strftime
:
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
这篇关于在 Python 中将数字格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!