Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer array to string in Python

I have an array of integer, and I need to transform it into string.

[1,2,3,4] => '\x01\x02\x03\x04'

What function can I use for it? I tried with str(), but it returns '1234'.

string = ""
for val in [1,2,3,4]:
    string += str(val) # '1234'
like image 367
prosseek Avatar asked Jun 12 '13 23:06

prosseek


People also ask

How do you convert an array of numbers to a string in Python?

Using map() Function str() function; that will convert the given data type into the string data type. An iterable sequence; each and every element in the sequence will be called by str() function. The string values will be returned through an iterator.

Can we convert int array to string?

toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space).

How do you convert int to string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How do you convert a list of integers to a list of strings in Python?

The most Pythonic way to convert a list of integers ints to a list of strings is to use the one-liner strings = [str(x) for x in ints] . It iterates over all elements in the list ints using list comprehension and converts each list element x to a string using the str(x) constructor.


2 Answers

''.join([chr(x) for x in [1, 2, 3, 4]])

like image 170
calccrypto Avatar answered Oct 05 '22 22:10

calccrypto


You can convert a list of small numbers directly to a bytearray:

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

And you can convert a bytearray directly to a str (2.x) or bytes (3.x, or 2.6+).

In fact, in 3.x, you can even convert the list straight to bytes without going through bytearray:

constructor arguments are interpreted as for bytearray().

So:

str(bytearray([1,2,3,4])) # 2.6-2.7 only
bytes(bytearray([1,2,3,4])) # 2.6-2.7, 3.0+
bytes([1,2,3,4]) # 3.0+ only

If you really want a string in 3.x, as opposed to a byte string, you need to decode it:

bytes(bytearray([1,2,3,4])).decode('ascii')

See Binary Sequence Types in the docs for more details.

like image 38
abarnert Avatar answered Oct 05 '22 23:10

abarnert