Python Converting A String to binary then an INT - python

I am working on an IPV4 breakdown where I have the necessary values in a string variable to represent the binary
(example: 00000000.00000000.00001111.11111111) This is a string
I need a way to turn this string into binary to then properly convert it to it's proper integer value
(in this case 0.0.15.255)
I've seen posts asking about something similar but attempting to apply it to what I'm working on has been unsuccessful
Apologies if this made no sense this is my first time posing a question here

You can achieve this using int() with base argument.
You can know more about int(x,base) - here
Split the string at '.' and store it in a list lst
For every item in lst, convert the item (binary string) to decimal using int(item, base=2) and then convert it into string type.
Join the contents of lst using .
s = '00000000.00000000.00001111.11111111'
lst = s.split('.')
lst = [str(int(i,2)) for i in lst]
print('.'.join(lst))
# Output
0.0.15.255

First split the string on . then convert each to integer equivalent of the binary representation using int builtin passing base=2, then convert to string, finally join them all on .
>>> text = '00000000.00000000.00001111.11111111'
>>> '.'.join(str(int(i, base=2)) for i in text.split('.'))
# output
'0.0.15.255'

You should split the data, convert and combine.
data = "00000000.00000000.00001111.11111111"
data_int = ".".join([str(int(i, 2)) for i in data.split(".")])
print(data_int) # 0.0.15.255

Welcome! Once you have a string like this
s = '00000000.00000000.00101111.11111111'
you may get your integers in one single line:
int_list = list(map(lambda n_str: int(n_str, 2), s.split('.')))

Related

How to split a string with an integer into two variables?

For example, is it possible to convert the input
x = 10hr
into something like
y = 10
z = hr
I considering slicing, but the individual parts of the string will never be of a fixed length -- for example, the base string could also be something like 365d or 9minutes.
I'm aware of split() and re.match which can separate items into a list/group based on delimitation. But I'm curious what the shortest way to split a string containing a string and an integer into two separate variables is, without having to reassign the elements of the list.
You could use list comprehension and join it as a string
x='10hr'
digits="".join([i for i in x if not i.isalpha()])
letters="".join([i for i in x if i.isalpha()])
You don't need some fancy function or regex for your use case
x = '10hr'
i=0
while x[i].isdigit():
i+=1
The solution assumes that the string is going to be in format you have mentioned: 10hr, 365d, 9minutes, etc..
Above loop will get you the first index value i for the string part
>>i
2
>>x[:i]
'10'
>>x[i:]
'hr'

How to Remove single Inverted comma from array in python?

I have the following array:
a =['1','2']
I want to convert this array into the below format :
a=[1,2]
How can I do that?
You can do it like that. You change each element of a (which are strings) in an integer.
a=[int(x) for x in a]
This single inverted comma you are talking about is the difference between str and int. This is pretty basic python stuff.
A string is a characters, displayed with the inverted comma's around it. 'Hello' is a string, but '1' can be a string too.
In you case ['1','2'] is a list of strings, and [1,2] is a list of numbers.
To convert a string to an int, you can do what is called casting. This is converting one type to another (They have to be compatible though.) Casting 'hello' to a number doesn't make sense and won't work.
Casting '1' to a number is possible by calling int('1') which will result in 1
In your case you can cast all elements in you list by calling a = [int(x) for x in a].
For more info on types see this article.
For information on list comprehensions (What I used to change your list) see this article.

List contain only one string in integer list

EDIT1:
i have problem about converting a string in a list. I collect only numbers from a file. Then convert them into integer. Using,
For line in range (0,len(file_name):
file_name[line] = int (file_name[line])
It worked, every number converted string to integer but only one number remain string. [2,4,'3']. Now, how can i convert that string into integer.
Thanks
You can do this in a list comprehension instead of a manual for loop.
file_name = [int(i) for i in file_name]

Python array data to integer

I have an array with 4 integer elements for example [1,0,1,0]
I want to convert it into string '1010'
How do that?
I've tried this
b=''.join(str(syndrome_noised.T))
print(b)
but I got '[1,0,1,0]'.
How this string without brackets.
The reason this fails is because you apply str(..) to the matrix. This will generate a single string. This string is however iterable, so you ''.join(..) the characters of that string back together, turning it into the original string again.
What you probably need to do, is convert every single element into a string, and then join these together, like:
b = ''.join(str(x) for x in syndrome_noised.T)
We thus iterate over the elements x in the syndrome_noised.T array, and we each time map it to a str(..), we then join these together.
We can shorten the code a bit, but still have the same semantics, with map:
b = ''.join(map(str, syndrome_noised.T))
syndrome_noised = [1,0,1,0]
''.join(str(x) for x in syndrome_noised)
you could do this by using a for loop like below:
text = str()
for i in array:
text += str(i)
print(text)
and that would return 1010

could not convert string to float (python)

I am trying to find the sum of all numbers in a list but every time I try I get an error that it cannot convert the string to float. Here is what I have so far.
loop = True
float('elec_used')
while (loop):
totalelec = sum('elec_used')
print (totalelec)
loop = False
You need none of your code above. The while loop is unnecessary and it looks like its just exiting the loop in one iteration i.e. its not used correctly. If you're simply summing all the values in the list:
sum([float(i) for i in elec_used])
If this produces errors, please post your elec_used list. It probably contains string values or blank spaces.
'elec_used' is of type string of characters. You can not convert characters to the float. I am not sure why you thought you could do it. However you can convert the numeric string to float by typecasting it. For example:
>>> number_string = '123.5'
>>> float(number_string)
123.5
Now coming to your second part, for calculating the sum of number. Let say your are having the string of multiple numbers. Firstly .split() the list, type-cast each item to float and then calculate the sum(). For example:
>>> number_string = '123.5 345.7 789.4'
>>> splitted_num_string = number_string.split()
>>> number_list = [float(num) for num in splitted_num_string]
>>> sum(number_list)
1258.6
Which could be written in one line using list comprehension as:
>>> sum(float(item) for item in number_string.split())
1258.6
OR, using map() as:
>>> sum(map(float, number_string.split()))
1258.6

Categories