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

128

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

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

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

总之,我需要哪个库/函数来执行这个操作?

9个回答

155

从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"}'

或者使用从2.7版本开始的str.format函数:

"{: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)

101

这里是一些使用现有字符串格式操作符(%)的示例,它已经存在了与Python一样长的时间(这意味着这个解决方案在Python 1.x、2.x和3.x中都兼容):

>>> "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开始(意味着适用于2.x和3.x),有一种替代方法:使用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特性(只适用于3.6及更高版本),我们需要相应的示例;是的,又是另一种选择:
>>> 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'

12

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}'

5

2
您可以使用以下内容来实现所需的功能。
"%d:%d:d" % (hours, minutes, seconds)

2
你可以使用str.format()方法将任何对象转换为字符串,从而使Python能够识别它们。

2
我已经在 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'>

0

str()在Python中作用于整数时将不会输出任何小数位。

如果你有一个浮点数想要忽略其小数部分,那么可以使用str(int(floatValue))。

或许以下代码能够说明:

>>> str(5)
'5'
>>> int(8.7)
8

0
如果你有一个包含小数的值,但小数部分可以忽略(例如:100.0),并且尝试将其转换成整数,你会得到一个错误。看起来很傻,但先调用float函数可以解决这个问题。
str(int(float([variable])))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接