118

我需要找出如何将数字格式化为字符串。我的代码在这里:

return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm

小时和分钟是整数,秒是浮点数。str() 函数会将所有这些数字转换为十分位 (0.1)。因此,我的字符串不是输出“5:30:59.07 pm”,而是显示类似“5.0:30.0:59.1 pm”的内容。

底线,我需要什么库/函数来为我做这件事?

4

9 回答 9

146

从 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)
于 2008-08-22T15:12:41.613 回答
98

以下是一些使用现有字符串格式运算符%

>>> "Name: %s, age: %d" % ('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 
'dec: 45/oct: 055/hex: 0X2D' 
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 
'http://xxx.yyy.zzz/user/42.html' 

从 Python 2.6 开始,有一个替代方法:str.format()方法。以下是与上述等效的片段,但使用的是str.format()

>>> "Name: {0}, age: {1}".format('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 
'dec: 45/oct: 0o55/hex: 0X2D' 
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 
'http://xxx.yyy.zzz/user/42.html'

与 Python 2.6+ 一样,所有 Python 3 版本(到目前为止)都了解如何做到这两点。我无耻地直接从我的核心 Python 介绍书和我不时提供的 Intro+Intermediate Python 课程的幻灯片中撕掉了这些东西。:-)

2018 年 8 月更新:当然,既然我们在 3.6 中引入了 f-string 功能,我们需要等效的示例;是的,另一种选择:

>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'

>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'

>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'

>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'

>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
于 2010-03-31T05:13:20.960 回答
9

Python 2.6+

可以使用该format()功能,因此在您的情况下,您可以使用:

return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)

有多种使用此功能的方法,因此有关更多信息,您可以查看文档

Python 3.6+

f-strings 是 Python 3.6 中添加到语言中的一项新功能。众所周知,这有助于格式化字符串:

return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'
于 2016-12-27T21:51:11.513 回答
4

您可以使用 C 风格的字符串格式:

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

见这里,尤其是:https ://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html

于 2008-08-22T15:13:45.667 回答
1

您可以使用以下功能来实现所需的功能

"%d:%d:d" % (hours, minutes, seconds)
于 2014-10-08T06:06:44.520 回答
1

您可以使用 str.format() 使 Python 将任何对象识别为字符串。

于 2019-07-23T13:46:16.870 回答
0

python 中的str()整数不会打印任何小数位。

如果您想要忽略小数部分的浮点数,则可以使用 str(int(floatValue))。

也许下面的代码会演示:

>>> str(5)
'5'
>>> int(8.7)
8
于 2008-08-24T10:32:49.317 回答
0

如果您有一个包含小数的值,但该十进制值可以忽略不计(即:100.0)并尝试对其进行 int,您将收到错误消息。看起来很傻,但首先调用 float 可以解决这个问题。

str(int(float([变量])))

于 2010-07-26T15:46:31.090 回答
0

我在 Python 3.6.9 中试过这个

>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)

<class 'str'>
于 2020-11-29T04:52:25.883 回答