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.
Related
I'm converting strings to floats using float(x). However for some reason, one of the strings is "71.2\x0060". I've tried following this answer, but it does not remove the bytes character
>>> s = "71.2\x0060"
>>> "".join([x for x in s if ord(x) < 127])
'71.2\x0060'
Other methods I've tried are:
>>> s.split("\\x")
['71.2\x0060']
>>> s.split("\x")
ValueError: invalid \x escape
I'm not sure why this string is not formatted correctly, but I'd like to get as much precision from this string and move on.
Going off of wim's comment, the answer might be this:
>>> s.split("\x00")
['71.2', '60']
So I should do:
>>> float(s.split("\x00")[0])
71.2
Unfortunately the POSIX group \p{XDigit} does not exist in the re module. To remove the hex control characters with regular expressions anyway, you can try the following.
impore re
re.sub(r'[\x00-\x1F]', r'', '71.2\x0060') # or:
re.sub(r'\\x[0-9a-fA-F]{2}', r'', r'71.2\x0060')
Output:
'71.260'
'71.260'
r means raw. Take a look at the control characters up to hex 1F in the ASCII table: https://www.torsten-horn.de/techdocs/ascii.htm
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.
(New to Python after years of R use)
Say I have a string:
dna = "gctacccgtaatacgtttttttttt"
And I want to pre-define the indices of interest:
window_1 = 0:3
window_2 = 1:4
window_3 = 2:5
This is invalid python syntax. So I tried:
window_1 = range(0, 3)
This does not work when I try to use the window_1 variable as a string index:
dna[window_1]
But I get "string indices must be integers" error.
I have tried numerous things such as wrapping range() in int() and / or list() but nothing works.
Thanks
When you're setting your variables window_1, window_2, and window_3, first you have to tell it where you want it to look to grab these indices you're telling it to grab, so you need to tell it to look in your variable 'dna'. Secondly, the indices should be in square brackets. Also keep in mind that Python uses a zero based numbering system. So, the first position in your dna sequence(g) as far as Python is concerned is the zero position. The second position (c) is actually the number 1 position.
dna = "gctacccgtaatacgtttttttttt"
window_1 = dna[0:3]
window_2 = dna[1:4]
window_3 = dna[2:5]
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
It seems as an easy question, but I cannot find the answer anywhere. If I have an integer variable, how can I transform it to a string with leading zeros?
I want something as the code below:
n = 4
string_size = 3
println(fleading(n, string_size))
# result should be "004"
Where fleading would be something like the function to transform the number to string with leading zeros. The analogous way in python is str(4).zfill(3) which gives 004 as result.
You're looking for the lpad() (for left pad) function:
julia> lpad(4,3,"0")
"004"
Note the last argument must be a string.
From the documentation:
lpad(string, n, "p")
Make a string at least n columns wide when printed, by padding on the left
with copies of p.
For Julia 1.0 the syntax is:
lpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ')
The example is therefore:
julia> lpad(4, 3, '0')
004
There is also #printf("%03i",4) using Printf.#printf