Juicy
Juicy

Reputation: 12520

List of ints to string

I have a list of ints:

(83, 105, 101, 109, 101, 110, 115)

which I believe codes for Siemens.

How can I convert this list to a string in a pythonic way?

I know I can get the individual chars with chr(x) and concatenate them but that doesn't seem the best way.

Upvotes: 2

Views: 221

Answers (3)

falsetru
falsetru

Reputation: 369054

Using bytes (or str) and bytearray:

>>> bytes(bytearray((83, 105, 101, 109, 101, 110, 115)))
'Siemens'

In Python 3.x:

>>> bytes((83, 105, 101, 109, 101, 110, 115)).decode()
'Siemens'

Upvotes: 4

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

t = (83, 105, 101, 109, 101, 110, 115)
print "".join(map(chr,t))
Siemens

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239463

For every number in the data, apply chr function to get the corresponding character and then concatenate all the characters together to get the actual string, like this

print "".join(chr(item) for item in (83, 105, 101, 109, 101, 110, 115))
# Siemens

Upvotes: 2

Related Questions