How to format a floating number to variable width in Python - python-3.x

I am writing code where I would like the user to enter the desire decimal point precision. For example:
for x in numbers:
print "{:10.*f}".format(x)
...except where the '*' is I would like to place a variable that which the user provided value. My search for a solution in available documentation has proved unfruitful.

How about print '{:10.{precision}f}'.format(x, precision=precision), where precision is a value defined elsewhere?

Python One-liner
number = 10.123456789
print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision"))))
Output :
>>> print ('{:10.{precision}f}'.format(number, precision=int(input("Enter the precision\n"))))
Enter the precision
5
10.12346

Related

Data Being Read as Strings instead of Floats

A Pytorch program, which I don't fully understand, produced an output and wrote it into weight.txt. I'm trying to do some further calculations based on this output.
I'd like the output to be interpreted as a list of length 3, each entry of which is a list of floats of length 240.
I use this to load in the data
w=open("weight.txt","r")
weight=[]
for number in w:
weight.append(number)
print(len(weight)) yields 3. So far so good.
But then print(len(weight[0])) yields 6141. That's bad!
On closer inspection, it's because weight[0] is being read character-by-character instead of number-by-number. So for example, print(weight[0][0]) yields - instead of -1.327657848596572876e-01. These numbers are separated by single spaces, which are also being read as characters.
How do I fix this?
Thank you
Edit: I tried making a repair function:
def repair(S):
numbers=[]
num=''
for i in range(len(S)):
if S[i]!=' ':
num+=S[i]
elif S[i]==' ':
num=float(num)
numbers.append(num)
num=''
elif i==len(S)-1:
num+=S[i]
num=float(num)
numbers.append(num)
return numbers
Unfortunately, print(repair('123 456')) returns [123.0] instead of the desired [123.0 456.0].
You haven't told us what your input file looks like, so it's hard to give an exact answer. But, assuming it looks like this:
123 312.8 12
2.5 12.7 32
the following program:
w=open("weight.txt","r")
weight=[]
for line in w:
for n in line.split():
weight.append(float(n))
print weight
will print:
[123.0, 312.8, 12.0, 2.5, 12.7, 32.0]
which is closer to what you're looking for, I presume?
The crux of the issue here is that for number in w in your program simply goes through each line: You have to have another loop to split that line into its constituents and then convert appropriately.

Converting a scientific notation string to an integer

I have a question in Python 3.7. I am opening a text file (input.txt) and creating variables from various lines of the text file. For example my text file looks as follows:
Case1
P
1.00E+02
5.
I need to create variables so that:
title = "Case1"
area = "P"
distance = 100
factor = 5
So far this is what I have:
f = open('C:\\input.txt',"r")
title = f.readline().strip()
area = f.readline().strip()
distance = f.readline().strip()
factor = f.readline().strip().strip(".")
f.close
print(title)
print(area)
print(distance)
print(factor)
which results in:
Case1
P
1.00E+02
5
How do I get the distance variable to show up as 100 instead of 1.00E+02?
I found the link below thinking it would help, but wasn't able to solve my problem from there. This is a very small segment of my larger program that was simplified, but if it works here it will work for my needs. My program needs to open a generated text file and produce another text file, so the scientific notation number will change between 1.00E-06 and 1.00E+03. The generated text file needs to have these numbers as integers (i.e. between 0.000001 and 1000). Thanks for any help!
Converting number in scientific notation to int
The link you posted actually gives the answer, albeit in a roundabout way.
int() cannot parse strings that don't already represent integers.
But a scientific number is a float.
So, you need to cast it to float first to parse the string.
Try:
print(float(distance))
For numbers with more decimals (e.g your example of 1.00E-06), you can force float notation all the time. Try:
print(format(float(distance), 'f'))
If you only want a certain number of decimals, try:
print(format(float(distance), '.2f'))
(for example)

Converting between a number to a string without num2str

For example, input is a=5678. How do you make b='5678'? (b is a String).
Not allowed to use str2num or any casting.
Is it possible to use log10? (I know how to do the reverse action).
[This is how I did the opposite (from string to num):
s = input('Enter a number: ','s');
x = sum(10.^(length(s-'0')-1:-1:0).*(s-'0'));
This looks like homework, so first here are some hints:
log10 may be useful to determine the number of digits.
mod can help to obtain each digit.
From your code for the reverse action: using successive powers of 10, as well as +'0' / -'0' to convert between digits and ASCII codes, may also be of help here.
And here's a possible approach using these hints (hover the mouse to find out):
b = char(mod(floor(a./10.^((ceil(log10(a))-1):-1:0)),10) + '0'):

num2str with a specific format in MATLAB

>> x = 14.021
>> num2str(x,'%4.5f')
I want to get this as a result:
0014.02100
But, MATLAB just answers me with:
14.02100
You should use sprintf. For example:
x = 14.021
sprintf('%010.5f', x)
Note that you don't need to use num2str.
The first argument to sprintf is the format specifier which describes how the resulting text should be displayed. The specifier begins with %, the leading 0 tells sprintf to pad the string with zeros. Loosely, the .5 tells it to print five digits to the right of decimal point and the f tells it we want to format it like a floating point number.

Fixed width number formatting python 3

How do I get an integer to fill 0's to a fixed width in python 3.2 using the format attribute?
Example:
a = 1
print('{0:3}'.format(a))
gives ' 1' instead of '001' I want. In python 2.x, I know that this can be done using
print "%03d" % number.
I checked the python 3 string documentation but wasn't able to get this.
http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language
Thanks.
Prefix the width with a 0:
>>> '{0:03}'.format(1)
'001'
Also, you don't need the place-marker in recent versions of Python (not sure which, but at least 2.7 and 3.1):
>>> '{:03}'.format(1)
'001'
Better:
number=12
print(f'number is equal to {number:03d}')
There is built-in string method .zfill for filling 0-s:
>>> str(42).zfill(5)
'00042'
>>> str(42).zfill(2)
'42'
In python 3, the prefered way is as follows:
use f-string (formatted string literal)
specify the width (the number after the colon) with a leading zero to indicate that you want zero rather than blank if the number is not larger enough.
For example:
a = 20
print(f"number is {a :03}")
Note that there is no space after the colon, otherwise the leading zero has no effect.

Resources