Fill up string of binary digits until certain length is reached - python

I have a string of ones and zeros, which typically has a length of 8*n, since they come from "n" bytes.
Now I want to arrange them into groups of five and I want to fill up the string with "0" until there are 16 5-bit "bytes" in total.
This is what I came up with but I can't figure out why this is not working.
while(len(binary_i) // (5*16) != 0):
binary_i = binary_i + "0"

Your problem seems to be that you're using // instead of %. Also, if you want to use a Python built-in alternative instead of using this while loop, try this:
binary_i.ljust(5*16, '0') # Fill `binary_i` using `0` up to 5*16 characters

Related

Set decimal on last two points

I dont find out how i can set the decimal (point) to the two last numbers...
I tried this '{0:.2f}'.format(a) but that makes like this '117085.00'
This is what i have
117085
55688
And i want
1170.85
556.88
So i need a point at the last two numbers.
And i dont want new numbers, i only need to set the point
Can someone help at this (easy i think) problem? :/ i am really new
In [33]: x = 117085
In [34]: x/100
Out[34]: 1170.85
The way that you are receiving your numbers, they are 100x the value you are trying to print. To format them the way you want, divide them by 100 before formatting them.
Additionally, the example you provide appears to be right-justified, meaning that the right side all lines up. If you want to accomplish that, you can use something like the below:
a = 117085
b = 55688
print('{0:>7.2f}'.format(a / 100))
print('{0:>7.2f}'.format(b / 100))
Output:
1170.85
556.88
Edit: Converted the rjust(7) to the format string >7
Let's break down the format string that we're using above...
{0:>7.2f} # The whole string
{ } # Brackets to denote a processed value
0 # Take the first argument passed through the `format()` function
: # A delimiter to separate the identifier (in this case, 0) from the format notation
>7 # Right justify this element, with a width of 7
.2f # Format the input as a float, with 2 digits to the right of the decimal point
Python implicitly assumes a few things apparently, so here's a shorter alternative:
{:7.2f} # The whole string
{ } # Brackets to denote a processed value
: # A delimiter to separate the identifier (in this case, assumed 0) from the format notation
7 # justify this element (Right justification by default), with a width of 7
.2f # Format the input as a float, with 2 digits to the right of the decimal point

Looping through an 8-byte hex code in python

I have an 8-byte hex code and i'm trying to loop through 00-FF for each byte starting from the last to the first but i'm new to python and i'm stuck.
here's the code for looping through 00-FF:
for h in range(0, 256):
return "{:02x}".format(h)
Essentially what i have is a
hexcode = 'f20bdba6ff29eed7'
EDIT: I'm going to add a little background information on this and remove my previous explanation. I'm writing a Padding Attack aglorithm with DES. Here's what needs to happen:
hexcode = 'f20bdba6ff29eed7'
for i in range(0,8):
(FOR i = 0 ) Loop through 00-FF for the last byte (i.e. 'd7') until you find the value that works
(FOR i = 1 ) Loop through 00-FF for the 7th byte (i.e. 'ee') until you find the value that works
and so on until the 1st byte
MY PROBLEM: my problem is that i dont know how to loop through all 8 bytes of the hex. This is easy when it's the 8th byte, because i just remove the last two elements and loop through 00-FF and add it back to hex to see if its the correct code. Essentially what the code does is :
remove last two elements of hex
try 00 as the last two elements
if the test returns true then stop
if it doesn't move to 01 (cont. through FF, but stop when you find the correct value)
My issue is, when its the bytes in the middle (2-7) how do i loop for a middle value and then add it all back together. Essentially
For byte 7:
Remove elements 13,14 from hex
try 00 as element 13,14
add hex[0:12] + 00 + hex [15:16]
if 00 returns true then stop, if not then loop through 01-ff until it does
and so on for bytes 6,5,4,3,2,1
Here's a quick way to break a string into chunks. We assume it has even length.
hexcode = 'f20bdba6ff29eed7'
l = len(hexcode)
for n in range(0, len(hexcode)/2):
index = n * 2
print hexcode[index:index+2]
If you need to operate on the string representations, you could easily generate a list of two character bytecodes using something similar to this. Personally, I prefer to operate on the bytes, and use the hexcodes only for IO.
[hexcode[n*2:n*2+2] for n in range(len(hexcode)/2)]

Strings, ints and leading zeros

I need to record SerialNumber(s) on an object. We enter many objects. Most serial numbers are strings - the numbers aren't used numerically, just as unique identifiers - but they are often sequential. Further, leading zeros are important due to unique id status of serial number.
When doing data entry, it's nice to just enter the first "sequential" serial number (eg 000123) and then the number of items (eg 5) to get the desired output - that way we can enter data in bulk see below:
Obj1.serial = 000123
Obj2.serial = 000124
Obj3.serial = 000125
Obj4.serial = 000126
Obj5.serial = 000127
The problem is that when you take the first number-as-string, turn to integer and increment, you loose the leading zeros.
Not all serials are sequential - not all are even numbers (eg FDM-434\RRTASDVI908)
But those that are, I would like to automate entry.
In python, what is the most elegant way to check for leading zeros (*and, I guess, edge cases like 0009999) in a string before iterating, and then re-application of those zeros after increment?
I have a solution to this problem but it isn't elegant. In fact, it's the most boring and blunt alg possible.
Is there an elegant solution to this problem?
EDIT
To clarify the question, I want the serial to have the same number of digits after the increment.
So, in most cases, this will mean reapplying the same number of leading zeros. BUT in some edge cases the number of leading zeros will be decremented. eg: 009 -> 010; 0099 -> 0100
Try str.zfill():
>>> s = "000123"
>>> i = int(s)
>>> i
123
>>> n = 6
>>> str(i).zfill(n)
'000123'
I develop my comment here, Obj1.serial being a string:
Obj1.serial = "000123"
('%0'+str(len(Obj1.serial))+'d') % (1+int(Obj1.serial))
It's like #owen-s answer '%06d' % n: print the number and pad with leading 0.
Regarding '%d' % n, it's just one way of printing. From PEP3101:
In Python 3.0, the % operator is supplemented by a more powerful
string formatting method, format(). Support for the str.format()
method has been backported to Python 2.6.
So you may want to use format instead… Anyway, you have an integer at the right of the % sign, and it will replace the %d inside the left string.
'%06d' means print a minimum of 6 (6) digits (d) long, fill with 0 (0) if necessary.
As Obj1.serial is a string, you have to convert it to an integer before the increment: 1+int(Obj1.serial). And because the right side takes an integer, we can leave it like that.
Now, for the left part, as we can't hard code 6, we have to take the length of Obj1.serial. But this is an integer, so we have to convert it back to a string, and concatenate to the rest of the expression %0 6 d : '%0'+str(len(Obj1.serial))+'d'. Thus
('%0'+str(len(Obj1.serial))+'d') % (1+int(Obj1.serial))
Now, with format (format-specification):
'{0:06}'.format(n)
is replaced in the same way by
('{0:0'+str(len(Obj1.serial))+'}').format(1+int(Obj1.serial))
You could check the length of the string ahead of time, then use rjust to pad to the same length afterwards:
>>> s = "000123"
>>> len_s = len(s)
>>> i = int(s)
>>> i
123
>>> str(i).rjust(len_s, "0")
'000123'
You can check a serial number for all digits using:
if serial.isdigit():

removing a % sign and parsing result as an integer

I am scraping an XML file and returning a load of percentages, pulled out directly as a percentage sometimes negative with the % sign already attached e.g.
-38%
-2%
4%
25%
I am trying to do a filter such as this:
if percentage < 20.0 : continue;
However I cannot perform this filter, I assume as a result of the % symbol.
For reference I use:
cell['roi']
To get the percentages, iterating through each row using:
for row in xmlload1['rows']:
cell = row["cell"]
How do I get around this % symbol? Is there an easy way?
You can't perform that filter because you're trying to compare a string (like "4%") to a float (20.0). In Python 3, this will raise a TypeError; in Python 2, it will "work", but all strings will be treated as greater than the number 20.0, so it won't do any good.
You need to convert the string to a float before you can use it as a float. But you don't want to convert the whole string, just the part before the "%" character. (Because 4% isn't a number, it's only the 4 that's a number.)
So, let's do it in two steps: use rstrip to remove the "%", then use float to convert it to a float.
cell = float(row["cell"].rstrip("%"))
You can pass a string to strip which will strip the characters passed in the passed string, the below will strip %, newlines and spaces:
cell = int(row["cell"].strip("%\n "))

Python: How to refer to a digit in a string by its index?

I feel like this is a simple question, but it keeps escaping me...
If I had a string, say, "1010101", how would I refer to the first digit in the string by its index?
You can get the first element of any sequence with [0]. Since a string is a sequence of characters, you're looking for s[0]:
>>> s = "1010101"
>>> s[0]
'1'
For a detailed explanation, refer to the Python tutorial on strings.
Negative indexes count from the right side.
digit = mystring[-1]
In Python, a sting is something called, subscriptable. That means that you can access the different parts using square brackets, just like you can with a list.
If you want to get the first character of the string, then you can simply use my_string[0].
If you need to get the last (character) in a string (the final 1 in the string you provided), then use my_string[-1].
If you originally have an int (or a long) and you are looking for the last digit, you are best off using % (modulous) (10101 % 10 => 1).
If you have a float, on the other hand, you are best of str(my_float)[-1]

Categories

Resources