[英]Python 2.7, Sypder, Keeping significant Figures from before a decimal
I am trying to figure out how to keep all significant figures in a value. 我试图找出如何将所有重要数字保持在一个值。 So for example let's say I want values 'a' and 'b':
例如,假设我想要值'a'和'b':
a = 00
b = 00
I want to be able keep both 0's but if it just reverts to '0'. 我想能够保持两个0,但如果它只是恢复为'0'。 I have tried adding a decimal, '.', after '00' but this just gives '0.0'.
我尝试在'00'之后添加一个小数'。',但这只是'0.0'。 For reference I am using this to create a file name for my code to read:
作为参考,我使用它来为我的代码创建一个文件名来读取:
filename = 'Folder/File' + str(a) + '-' str(b) + '.file'
where the 'b' would be restated once a loop is completed: 一旦循环完成,'b'将被重述:
b += 10
with the hope that this sets a to be '01' and so on. 希望这将a设置为'01'等等。 I then state that if b reaches a certain number then the 'a' value is restated and 'b' reset to '00':
然后我声明如果b达到某个数字,则重新设置'a'值并将'b'重置为'00':
if b > 50:
a += 1
b = 00
As might be obvious this is my attempt to basically set up a 'time'-like function. 很明显,这是我试图基本上建立一个'时间'的功能。 This is because the part of the filenames that change are the time they were made.
这是因为更改的文件名部分是它们的制作时间。 This is maddening because I am working with 2670+ files and I need a good way to set them up for reading.
这很令人抓狂,因为我正在处理2670多个文件,我需要一个很好的方法来设置它们进行阅读。
您可以在计算filename
时使用字符串格式来创建填充,而不是尝试填充a
和b
:
filename = 'Folder/File%02d-%02d.file' % (a, b)
In computer languages, numbers are stored internally in binary and have no concept of formatting. 在计算机语言中,数字以二进制形式存储在内部,并且没有格式化的概念。 16, 0x10, 0b10000 are all ways to format the number 16.
16,0x10,0b10000是格式化数字16的所有方法。
Python has string formatting to help with this: Python有字符串格式来帮助解决这个问题:
>>> x = 16
>>> format(x,'x') # format as hexadecimal
'10'
>>> format(x,'b') # format as binary
'10000'
>>> format(x,'#x') # hexadecimal with indicator
'0x10'
>>> format(x,'#b') # binary with indicator
'0b10000'
>>> format(x,'4') # decimal with minimal length 4
' 16'
>>> format(x,'04') # decimal with mimimal length 4 and leading zeroes
'0016'
You can embed formatting in a format string, and specify different formats for the same parameter by index. 您可以在格式字符串中嵌入格式,并通过索引为同一参数指定不同的格式。 Below formats the first parameter (index 0) three different ways:
下面以三种不同的方式格式化第一个参数(索引0):
>>> '{0} {0:#x} {0:#b}'.format(16)
'16 0x10 0b10000'
In Python 3.6, there are new formatting strings that simplify the syntax: 在Python 3.6中,有一些新的格式化字符串可以简化语法:
>>> a,b,c=1,2,3
>>> f'{c} {b} {a:02}'
'3 2 01'
For your example: 对于你的例子:
filename = 'Folder/File{:02}-{:02}.file'.format(a,b)
See Format Specification Mini-Language . 请参阅格式规范迷你语言 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.