How does '%.*g' % (6,k) work in python - python

I have the following piece of code: (Python 2.7)
k = 4535.65463456
out = '%.*g' % (6,k)
print str(out)
Output: 4535.65
I am not able to understand the working of '%.*g' % (6,k). Since I not familiar with this syntax and don't know what this is called, I am not even able to google it. Could someone help me with this?
Thanks in advance.

With C-borrowed syntax "%6g" you're able to tell python to display your float with a maximum of six digits (if the number isn't too large).
It means that if the integer part of the number has 4 digits, it will use the 2 remaining digits to print the most significant decimal part.
Now if we want to make it parametrizable, we have to generate the format string, which isn't very convienient, so Python introduced Parametrized precision in such strings.
'%.*g' % (6,k)
prints k with 6 digits max.
Now you'll be better of the "new" formatting using format, which allows "nested" formatting to generate the outer formatting (so no need for intricate .* syntax):
'{:.{prec}g}'.format(k, prec=6) # courtesy of Dan comment
Here prec isn't even a special keyword, just the parameter name passed as a function keyword. This is like:
'{:6g}'.format(k)
There's an entire website dedicated to python old & new style formats: https://pyformat.info/
(and there's also a newer syntax with Python 3.6 format strings... https://www.python.org/dev/peps/pep-0498/)

out = '%.*g' % (6,k)
that mean it will print the nember after ,6 ; look at '%.' %. = 4535. , that will be printed then '.*g' , * = 6 , the number after the ',' then g = 5 then number after 6

Related

How to convert to Python 3

I am in the process of converting Python 2 code into Python 3. Currently I am facing difficulty in converting the following code to Python 3. Please help.
print 'Data cache hit ratio: %4.2f%%' % ratio
Also, what %4.2f%% means?
Tried to rewrite the code with format().
Just put parens around the parameters.
print('Data cache hit ratio: %4.2f%%' % ratio)
There are fancier ways of doing formatting in Python 3, but that will work.
%4.2f says "display this floating point number in a 4-character field with a decimal point and two places after. So, like "9.99". %% says "display a percent sign". The formatting here is straight from the C printf function.
f denotes the fixed point notation. The value that precedes with % (4.2) is for denoting the width (4) and the precision (2) of the number respectively.
You can use either .format or f string
print("Floating point {0:4.2f}".format(ratio))
print(f' Floating point {ratio:4.2f}')
Here 4 is the total width of the field being printed, lefted-padded by spaces. 2 is the number of digits after the decimal point. You can read more about it here https://docs.python.org/3/library/string.html#format-specification-mini-language

Python output formats

Hi there I've had a search output formats and formats had no luck. I couldn't find right documentation for it and I really want to learn how this code works if somebody could enlighten me please?
print ("Survived: %i (%.1f%%)"%(len(survived), float(len(survived))/len(train)*100.0))
print ("Not Survived: %i (%.1f%%)"%(len(not_survived), float(len(not_survived))/len(train)*100.0))
print ("Total: %i"%len(train))
My questions is inside the code % symbols %i %.1f%% (I believe one decimal) I just really struggle understanding this code how it works (%%%) wise. if somebody could break down for me.
Output is:
Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891
Thank you.
Python supports different ways of formatting strings. Unfortunately, they are not all in the same place in the documentation. So, I guess it makes sense to put them all in one SO answer :)
What you have in the question is printf-style formatting using the modulo (%) operator. For the specification of that see printf-style String Formatting.
Example:
x = 9
print('value of x is %d' % x)
For formatting using the format function, see Format String Syntax.
Example:
x = 9
print('value of x is {x}'.format(x=x))
The same syntax is used as basis for f-strings. See PEP-0498.
Example:
x = 9
print(f'value of x is {x}')
There are also template strings, see Template strings specification.
Example:
x = 9
print(string.Template('value of x is $x').substitute(x=x))

Answer is only printing .0 instead of .00 in python [duplicate]

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 → 5.00, 5.5 → 5.50, etc). How can I do this in Python?
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
f-string formatting:
This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.
Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Use round() - mostly for display purpose.
String formatting:
print "%.2f" % 5
If you actually want to change the number itself instead of only displaying it differently use format()
Format it to 2 decimal places:
format(value, '.2f')
example:
>>> format(5.00000, '.2f')
'5.00'
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
Shortest Python 3 syntax:
n = 5
print(f'{n:.2f}')
In Python 3
print(f"{number:.2f}")
A shorter way to do format.
I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:
Python 3:
>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict)
0.12_0.13
I faced this problem after some accumulations. So What I learnt was to multiply the number u want and in the end divide it to the same number. so it would be something like this: (100(x+y))/100 = x+y if ur numbers are like 0.01, 20.1, 3,05.
You can use number * (len(number)-1)**10 if your numbers are in unknown variety.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
Using Python 3 syntax:
print('%.2f' % number)

Remove decimal number from the function eval() [duplicate]

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

Strict Python formatting for floats

I'm using PYTHON to write to a file where the formatting is very strict. I have 10 available spaces in each column which cannot be exceeded.
I want to write the as many decimals as I can, but if the number is negative, the minus sign must be preferred over the last decimals. Also the period in the float must be counted into the number of available spaces. Numbers should be right trunctated
Example:
Let's say I want to print two numbers
a = 123.4567891011
b = 0.9876543210
Then I would want the result:
123.4567890.98765432
But if I now have the following:
a = -123.1111111111
b = 98765.432101234
c = 567
d = 0.1234
Then I'd want:
-123.1111198765.4321 567.0 0.1234
Would be to nice use exponential notation for high numbers, but not a necessity. I'm unable to find the answer. All I can find is to fix the format to number of significant digits, which really won't help me.
I've tried several methods of the
f.write({0:>10}{1:>10}.format(a,b))
but can't figure it out. Hope you see what I`m looking for.
Okay, so I found a way. I basically convert everything to strings and use:
f.write("{0:>10.10}{1:>10.10}".format(str(a),str(b)))
and so on..

Categories

Resources