问题:在Python中将数字格式化为字符串
我需要找出如何将数字格式化为字符串。我的代码在这里:
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
小时和分钟是整数,而秒是浮点数。str()函数会将所有这些数字转换为十分之几(0.1)。因此,而不是我的字符串输出“ 5:30:59.07 pm”,它将显示类似“ 5.0:30.0:59.1 pm”的内容。
最重要的是,我需要为我执行什么库/函数?
I need to find out how to format numbers as strings. My code is here:
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
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?
回答 0
从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)
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"}'
or the str.format
function starting with 2.7:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
or the string formatting %
operator for even older versions of Python, but see the note in the docs:
"%02d:%02d:%02d" % (hours, minutes, seconds)
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)
回答 1
从Python 2.6开始,有一个替代str.format()
方法:方法。以下是使用现有字符串格式运算符(%
)的一些示例:
>>> "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'
以下是等效片段,但使用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-串功能,我们需要的相同的例子是,是的另一种选择:
>>> 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'
Starting in Python 2.6, there is an alternative: the str.format()
method. Here are some examples using the existing string format operator (%
):
>>> "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'
Here are the equivalent snippets but using 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'
Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)
Aug 2018 UPDATE: Of course, now that we have the f-string feature in 3.6, we need the equivalent examples of that, yes another alternative:
>>> 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'
回答 2
Python 2.6以上
可以使用该format()
功能,因此您可以使用:
return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)
有多种使用此功能的方法,因此,有关更多信息,请查看文档。。
Python 3.6+
f字符串是Python 3.6中已添加到该语言的一项新功能。众所周知,这有助于格式化字符串:
return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'
Python 2.6+
It is possible to use the format()
function, so in your case you can use:
return '{:02d}:{:02d}:{:.2f} {}'.format(hours, minutes, seconds, ampm)
There are multiple ways of using this function, so for further information you can check the documentation.
Python 3.6+
f-strings is a new feature that has been added to the language in Python 3.6. This facilitates formatting strings notoriously:
return f'{hours:02d}:{minutes:02d}:{seconds:.2f} {ampm}'
回答 3
回答 4
您可以使用以下代码来实现所需的功能
"%d:%d:d" % (hours, minutes, seconds)
You can use following to achieve desired functionality
"%d:%d:d" % (hours, minutes, seconds)
回答 5
您可以使用str.format()使Python识别字符串中的任何对象。
You can use the str.format() to make Python recognize any objects to strings.
回答 6
python中的str()在整数上不会显示任何小数位。
如果您有一个要忽略小数部分的浮点数,则可以使用str(int(floatValue))。
也许以下代码将演示:
>>> str(5)
'5'
>>> int(8.7)
8
str() in python on an integer will not print any decimal places.
If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).
Perhaps the following code will demonstrate:
>>> str(5)
'5'
>>> int(8.7)
8
回答 7
如果您有一个包含小数的值,但是该十进制的值可以忽略不计(即:100.0),并尝试将其设为int,则会出现错误。看起来很傻,但是先调用float可以解决此问题。
str(int(float([variable])))
If you have a value that includes a decimal, but the decimal value is negligible (ie: 100.0) and try to int that, you will get an error. It seems silly, but calling float first fixes this.
str(int(float([variable])))