Convert a list of integers to string - python

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)

Related

Append strings of different length to array

I try to append content from a list looking like this: ["a", "b", "cd"] to an array. It is possible to append "single" strings like "a" and "b" but how do I append the "cd" ?
from array import array
def function(a):
our_array = array("u",[])
our_array.insert(0,a)
print(our_array)
#Working
function("a")
#Not working
function("cd")
array("u",[]) means that the type of our_array elements is wchar_t (docs). As the "cd" is not wchar_t you can't put it into this array. You can use list for that purpose. For example:
def function(a):
our_list = []
our_list.append(a)
print(our_list)
The array interface only allows adding a single element using .append, and the string 'ab' is not a single element for an array of the u type.
Suppose we have an existing array
x = array('u', 'cd')
To prepend 'ab', simply make another array from that string, and then insert it by using slicing:
x[:0] = array('u', 'ab')
Or concatenate the arrays and assign back:
x = array('u', 'ab') + x
Or iterate over the string:
for position, c in enumerate('ab'):
x.insert(position, c)
Note that each insertion changes the position where the next value should be inserted, so we need to count upwards with the index. enumerate is the natural tool for that.
"".join() allows you to do exactly that.
I refactored the function like so:
def function(a):
letters = []
for letter in a:
letters.append(letter)
our_array = array("u","".join(letters))
print(our_array)

Python convert array of strings to array of bytes

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']

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.

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.

Remove single quotes from python list item

Actually quite simple question:
I've a python list like:
['1','2','3','4']
Just wondering how can I strip those single quotes?
I want [1,2,3,4]
Currently all of the values in your list are strings, and you want them to integers, here are the two most straightforward ways to do this:
map(int, your_list)
and
[int(value) for value in your_list]
See the documentation on map() and list comprehensions for more info.
If you want to leave the items in your list as strings but display them without the single quotes, you can use the following:
print('[' + ', '.join(your_list) + ']')
If that's an actual python list, and you want ints instead of strings, you can just:
map(int, ['1','2','3','4'])
or
[int(x) for x in ['1','2','3','4']]
Try this
[int(x) for x in ['1','2','3','4']]
[1, 2, 3, 4]
and to play safe you may try
[int(x) if type(x) is str else None for x in ['1','2','3','4']]

Categories

Resources