Python convert array of strings to array of bytes - python

I am trying to convert an array of strings oldlist = ['00000100', '10100001', '11000001', '11100001'] that are binary values into bytes of their value as hex codes so the resulting list would look like this newlist = [b'\x04', b'\xa1', b'\xc1', b'\xe1']. I get the basic concept of looping through the first list and appended to the previous or doing some sort of list comp. But I can't find a function to convert "00000100" to " b'\x04' "

You can use int(number, 2) to convert the string to integer:
oldlist = ["00000100", "10100001", "11000001", "11100001"]
out = list(map(lambda x: bytes([int(x, 2)]), oldlist))
print(out)
Prints:
[b'\x04', b'\xa1', b'\xc1', b'\xe1']

what you can do is to use string.getBytes();

You first need to convert the binary string to an integer. For this you can use int() method with radix of 2. Then to convert that to bytes, use the bytes() method like this bytes([x]).
>>> oldlist = ['00000100', '10100001', '11000001', '11100001']
>>> list(map(lambda x: bytes([int(x, 2)]), oldlist))
[b'\x04', b'\xa1', b'\xc1', b'\xe1']

Related

list of strings to a tuple of ints

I'm new to python and am having trouble doing this conversion. How exactly do you convert a list of individual strings such as ['1','2'] and convert it to a tuple (1,2). If it was simply a list it would be simple to just use tuple(list_x) but this seems more complicated.
You can use the tuple constructor to make a tuple from a list:
X = ['1', '2']
myTuple = tuple(X)
myTuple is now a tuple of strings: ('1', '2').
If you want to get a tuple of integers, you must first convert your list to a list of integers, and then use the tuple constructor.
The int() function will convert a string to an int. We can use that plus a list comprehension to get what you want:
tuple([int(s) for s in X])
List ['1', '2'] can be converted to tuple by line below:
l = ['1','2']
tuple_from_l = tuple(map(int,l))
print tuple_from_l
Note: Before converting to tuple i've passed list to map to convert all item to int with int method

Writing a nested loop in python [duplicate]

This question already has answers here:
how to change [1,2,3,4] to '1234' using python
(2 answers)
Closed 7 years ago.
I'm a Python beginner struggling to write code that uses the list myList = [['A','B','C'],[4,5,​6],[7,8,9]] and generates the output below:
Input:
myList = [['A','B','C'],[4,5,​6],[7,8,9]]
Expected output: (by line)
-A-B-C-
-4-5-6-
-7-8-9-
I've tried a few different things but am not sure how to approach the confluence of strings and integers in the same list.
I can get:
>>> for i in range (0,myList_len):
... print ("-".join(myList[i]))
...
A-B-C
But I can't get this to work for the numbers. Any help would be much appreciated!
You could use map to convert from int to str
for l1 in myList:
print '-' + '-'.join(map(str, l1)) + '-'
When you try to join numbers, you get the following error:
TypeError: sequence item 0: expected str instance, int found
This is because str.join() only works with str items in the iterable, but you pass it int objects instead.
So in order to properly join them, you need to convert them to strings first. You can either do that by calling str on every item using map, or by using a list comprehension:
>>> lst = [4, 5, 6]
>>> '-'.join(map(str, lst))
'4-5-6'
>>> '-'.join([str(x) for x in lst])
'4-5-6'
The "join" operator expects a list of strings, so you have to turn your numbers to strings first, using the "str" operator that turns anything into a string.
for l in myList:
print '-' + '-'.join([str(x) for x in l]) + '-'
join works on strings, not numbers. You need to convert:
print ("-".join(str(num) for num in myList[i]))
Now, just add the hyphens at start and finish, and you're done.
Try the following:
for sublist in myList:
print("-".join(map(str, sublist)))
The output is:
A-B-C
4-5-6
7-8-9
If you want leading and trailing hyphens as well, use:
for sublist in myList:
print("-" + "-".join(map(str, sublist)) + "-")
The output is:
-A-B-C-
-4-5-6-
-7-8-9-
The for loop iterates over the sublists. The map(str, sublist) call applies str to each element of the sublist, converting it to a string. Without this, your non-string entries (i.e., numbers) were causing errors when passed to join.

Python: How to convert a list to a list of tuples?

for example, i have a list below,
['Visa', 'Rogers', 'Visa']
if i want to convert it to a list of tuples, like
[('Visa',), ('Rogers',), ('Visa',)]
How can I convert it?
>>> [(x,) for x in ['Visa', 'Rogers', 'Visa']]
[('Visa',), ('Rogers',), ('Visa',)]
simple list comprehension will do the trick. make sure to have the , to specify single item tuples (you will just have the original strings instead)
Doing some kind of operation for each element can be done with map() or list comprehensions:
a = ['Visa', 'Rogers', 'Visa']
b = [(v,) for v in a]
c = map(lambda v: (v,), a)
print(b) # [('Visa',), ('Rogers',), ('Visa',)]
print(c) # [('Visa',), ('Rogers',), ('Visa',)]
Please keep in mind that 1-element-tuples are represented as (value,) to distinguish them from just a grouping/regular parantheses

Convert list to string using python

I have the list it contain int ,float and string:
lists = [10, "test", 10.5]
How Can i convert above list to string? I have tried:
val = ','.join(lists)
print val
I am getting error like this:
sequence item 0: expected string, int found
How can I solve this issue?
Firstly convert integers to string using strusing map function then use join function-
>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'
Or if you want to convert each element of list into string then try-
>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']
Or use itertools for memory efficiency(large data)
>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']
Or simply use list comprehension
>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']
The easiest way is to send the whole thing to str() or repr():
>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"
repr() may produce a different result from str() depending on what's defined for each type of object in the list. The point of repr() is that you can send such strings back to eval() or ast.literal_eval() to get the original object back:
>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]
a = ['b','c','d']
strng = ''
for i in a:
strng +=str(i)
print strng
The error you are getting because join wants elements to be string type, but in your list there is integer too, so 1st you have to convert them to type string.
you can use list comprehension and str and join to join them
>>> lists = [10,"test",10.5]
>>> ",".join(str(x) for x in lists)
You have to pass each item in your list as a string into the ','.join(sequence). Consider using:
val = ','.join([str(item) for item in lists])
print val
If you want to convert each element in the list to a string, you could do it simply using a for-loop.
for i in range(len(lists)):
lists[i] = str(lists[i])
Alternatively, if you want to make one string where all elements are joined together, you could edit the code above slightly.
string_of_lists = ""
for i in lists:
string_of_lists += str(i)
As you can tell, this is another way of doing it, apart from the other solutions using join.
I hope I helped!
This is also possible. Here x variable is list.
>>> '%s'*len(x) % tuple(x)
As mentioned here
list=['a/b/c', 'd/e/f']
file_list_string= ' '.join(list)
file_list_string= ' '.join(str(file) for file in list)
import functools
lists = [10,"test",10.5]
print(functools.reduce(lambda x,y:x+","+y,list(map(str,lists))))
You could always do it the dirty way:
list_name = ["a", "b", "c"];
string_name = "";
for c in list_name:
string_name += c
print(string_name)
OUTPUT:
"abc"
That should work with ints, floats, and strings, always converting them to string type.

Convert a list of integers to string

I want to convert my list of integers into a string. Here is how I create the list of integers:
new = [0] * 6
for i in range(6):
new[i] = random.randint(0,10)
Like this:
new == [1,2,3,4,5,6]
output == '123456'
With Convert a list of characters into a string you can just do
''.join(map(str,new))
There's definitely a slicker way to do this, but here's a very straight forward way:
mystring = ""
for digit in new:
mystring += str(digit)
two simple ways of doing this
"".join(map(str, A))
"".join([str(a) for a in A])
Coming a bit late and somehow extending the question, but you could leverage the array module and use:
from array import array
array('B', new).tobytes()
b'\n\t\x05\x00\x06\x05'
In practice, it creates an array of 1-byte wide integers (argument 'B') from your list of integers. The array is then converted to a string as a binary data structure, so the output won't look as you expect (you can fix this point with decode()). Yet, it should be one of the fastest integer-to-string conversion methods and it should save some memory. See also documentation and related questions:
https://www.python.org/doc/essays/list2str/
https://docs.python.org/3/library/array.html#module-array
Converting integer to string in Python?
If you don't like map():
new = [1, 2, 3, 4, 5, 6]
output = "".join(str(i) for i in new)
# '123456'
Keep in mind, str.join() accepts an iterable so there's no need to convert the argument to a list.
You can loop through the integers in the list while converting to string type and appending to "string" variable.
for int in list:
string += str(int)

Categories

Resources