I am producing a large output file, which goes over several lines. This is a shortened version of a section I hope to produce.
line = \
f"""
Output: {a} {b:0.10f} {c:0.8f}
"""
where a, b, and c are floats of variable length.
In the example above, I have managed to shorten the b float and c float to 10 decimal places and 8 decimal places respectively.
However, I am hoping to get a string which when printed looks like:
Output: 10.05 0.0987654321 0.87654321
Where the spacing between the values can be controlled individually and is not necessarily equal. Essentially, I hope to lock the values in position.
This is made difficult by the fact that a could also be a tuple of varying length (which impacts the positioning of the floats).
Is this possible without the .format() method?
If not, how should the .format() method be used correctly?
Put the space before the specifier and drop the 0 prefix for the float
The value before the . is the padding and position, and not necessarily the 0-prefix for a float
>>> f"Output: {a} {b:.10f} {c:.8f}"
'Output: 10.05 0.0987654321 0.87654321'
>>> f"Output: {a: <5} {b: >15.10f} {c:0>15.8f}"
'Output: 10.05 0.0987654321 000000.87654321'
Related
I am having a hard time trying to figure out why I am getting the result with my code that I am getting.
c = int(format(ord('c'), 'b'))
h = int(format(ord('h'), 'b'))
result = c | h
print(c)
print(h)
print(result)
This returns a result of:
1100011
1101000
1101035
So my question is after the | operation, why is it 1101035 when (according to my understanding) it should be 1101011?
The call to format with the second argument being "b" gives you the binary representation of the number in the first argument. So, if you print it, you will see the "0"s and "1"s.
However, when you use int on this result, withug informing int that your string is base 2, it thinks these are decimal numbers. So, it will "read" the sequence "1100011" (the binary representation of 99, the unicode codepoint for the "c" character), as "1_100_011", or "one million, one hundred thousand and eleven" - and that is the number in your c variable if you print or make any numeric operations with it.
This can be easily solved by telling int that the numeric strings you are reading are binary themselves:
c = int(format(ord('c'), 'b'), 2)
(Passing 2 as the second argument to "int" to indicate the base). If you inspect "c" at this point, it contains the number 99, which will behave as expected with your "|" operator. Of course, if you are not looking at the binary representation of the number, there is no point in generating it to start with, so your code could be just c = ord('c')...
Doing int() here makes no sense (it's taking your string of binary bits and interpreting them as a decimal number). You just want:
c = ord('c')
h = ord('h')
result = c | h
print(format(c, 'b'))
print(format(h, 'b'))
print(format(result, 'b'))
(only using format for display on screen, not for calculation!)
which prints:
1100011
1101000
1101011
The output value is not including the 0's in the beginning, can someone help me fix the problem?
def bitwiseOR(P, Q):
return bin(P | Q)
bitwiseOR(0b01010111, 0b00111000)
OUTPUT: '0b1111111'
The leading zeroes are just for representation, so you can utilize Format Specification Mini-Language to display them as you wish:
Format string:
# Includes 0b prefix
0{length} Pad leading zeroes so total length is length
def bitwiseOR(P, Q, length=10):
return format(P | Q, f'#0{length}b')
x = bitwiseOR(0b01010111, 0b00111000)
# 0b01111111
print(x)
Leading zeros are a property of the string you produce, not the number. So, for example, if you're looking for a way to make the following two calls produce different results, that's not possible:1
bitwiseOR(0b01010111, 0b00111000)
bitwiseOR( 0b1010111, 0b111000)
However, if you can provide the number of digits separately, then you can do this using the format() function. It accepts a second argument which lets you customize how the number is printed out using the format spec. Based on that spec, you can print a number padded with zeros to a given width like this:
>>> format(127, '#010b')
'0b01111111'
Here the code consists of four pieces:
# means apply the 0b prefix at the beginning
0 means pad with leading zeros
10 means the total length of the resulting string should be at least 10 characters
b means to print the number in binary
You can tweak the format code to produce your desired string length, or even take the length from a variable.
1Well... technically there is a way to make Python re-read its own source code and possibly produce different results that way, but that's not useful in any real program, it's only useful if you want to learn something about how the Python interpreter works.
I am using Python for reading a file and converting numerical value written as string to float. I observe a weird conversion:
a="-5.970471694E+02"
b = float(a)
b
>> -597.0471694
bb = np.float64(a)
bb
>> -597.04716940000003
e="-5.970471695E+02"
ee = np.float64(e)
ee
>> -597.0471695
ee-bb
>> -9.9999965641472954e-08
What is the reason of the term "0000003" at the end of bb. Why I don't observe the same thing for ee. Is this really a problem? I think this issue is due to the floating-point accuracy but the result seems to be perturbed before I start to use the variables...
What is the reason of the term "0000003" at the end of bb. Why I don't observe the same thing for ee.
b and bb have identical values (try evaluating b == bb). The difference comes down to how they are represented by the interpreter. By default, numpy floats are displayed with 8 digits after the decimal place, whereas Python floats are printed to 13 significant digits (including those before the decimal place).
Is this really a problem?
Since the actual values of b and bb are identical then the answer is almost certainly no. If the display differences bother you, you can use np.set_printoptions to control how numpy floats are represented in the interpreter. If you use IPython, you can also use the %precision magic to control how regular Python floats are printed.
Both float and float64 use a binary representation of the number. Both have to save the approximation that is caused by conversion from the number with base 10 to the number with base 2. The float uses less bits, so the error is greater and it is made visible when the a is copied to b. That is because b takes the a including the rounding error without the loss of information, and the a contains that 000..03 value. In other words, it is a rounding error from converting a decimal number to a binary number.
I want my Python (2.4.3) output numbers to have a certain format. Specifically, if the number is a terminating decimal with <= 6 significant digits, show it all. However, if it has > 6 significant digits, then output only 6 significant digits.
"A" shows how Python is writing the floats. "B" shows how I want them written. How can I make Python format my numbers in that way?
A:
10188469102.605597
5.5657188485
3.539
22.1522612479
0
15.9638450858
0.284024
7.58096703786
24.3469152383
B:
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469
You'll want the g modifier for format that drops insignificant zeroes;
>>> "{0:.6g}".format(5.5657188485)
'5.56572'
>>> "{0:.6g}".format(3.539)
'3.539'
Sorry, my update also includes the fact that I am restricted to using
Python 2.4.3, which does not have format() function.
The format specifiers work even without the .format() function:
>>> for i in a:
... print '%.6g' % (i,)
...
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469
There is a way to retain trailing zeros so that it consistently shows the number of significant digits. Not exactly what OP wanted, but probably useful to many.
a = [10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]
for i in a:
print("{:#.6g}".format(i))
Output
1.01885e+10
5.56572
3.53900
22.1523
0.00000
15.9638
0.284024
7.58097
24.3469
Note that this will only work with the format function and not with % operator.
According to the docs:
The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float, complex and Decimal types.
'g': General format ... insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.
try this way
a=[10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]
for i in a:
if i >100:
print '{:.6e}'.format(i)
else:
print '{:.6f}'.format(i)
for lower version of python
for i in a:
if i >100:
print '%6e'%i
else:
print '%6f'%i
output
1.018847e+10
5.565719
3.539000
22.152261
0.000000
15.963845
0.284024
7.580967
24.346915
I have what I believe to be a simple question. I have the following code and the output is not what I expect:
import socket
import time
r=031508.78
h=373309.9
z=0
mes='"TSRA %s %s %s\r\n"'%(r,h,z)
print mes
My problem is that r prints as '31508.78' and I want '031508.78'. How I get preserve the leading zero?
The 0 in front of the number is not important for python, because numbers have no leading 0s. You can use:
print '%09.2f'%r
I prefer the new string format mini language. I find it more intuitive.
r = 31508.78
h = 373309.9
z = 0
print '"TSRA {0: 011.3f} {1: 011.3f} {2}"\r\n'.format(r, h, z)
print '{0: 011.3f}\n{1: 011.3f}\n{2: 011.3f}'.format(r, h, z)
{0: 011.3f} 0: indicates the first item (r). 011 tells the formatter that there will be 11 characters including the decimal point and a place holder for a negative sign. By placing a 0 in front the formatter will pad the space with leading zeros. Finally, .3f indicates the precision and a fixed number of places after the decimal point.
Yields:
"TSRA 031508.780 373309.900 0"
031508.780
373309.900
000000.000
I don't think there is any way to store a number with a leading zero in python.
This leaves you with two ways:
1) Make r a string i.e. r="031408.78"
I think this is the best method for you as you can do all the arithmetic you want to do (using the implicit typecasting of python) and see the number appended with a 0 wherever you use it.
2) If you simply want to print the number with leading zeros consider using this
print "%09.2f' % r #for this you need the length of the number
For Python, there is no difference in the following things:
31508.78
031508.78
0000000031508.78
31508.7800000000000
0000000000000031508.7800000000000
Those are all valid representations of the exact same number, which is canonically represented by 31508.78, which is essentially just a convention. Different representations are possible too, and actually, the number is represented in a way that’s described by the IEEE-754 standard.
So, when you want that leading zero, you have to tell Python explicitely to put it there because it simply doesn’t know about it. You just used one of many valid representations to specify that one number which default string representation does not include leading zeroes.
The best way to do this is using string formatting, which comes in two flavors. The old style flavor, using the % operator, and the newer str.format function:
>>> '%09.2f' % 31508.78
'031508.78'
>>> '{:09.2f}'.format(31508.78)
'031508.78'
Or, if you don’t actually want a number, you could also just specify the number as a string to begin with, which of course keeps the leading zero.