Friday, February 11, 2011

How do I convert a list of ascii values to a string in python?

I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?

  • You are probably looking for 'chr()':

    >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
    >>> ''.join(chr(i) for i in L)
    'hello, world'
    
  • l = [83, 84, 65, 67, 75]
    
    s = "".join([chr(c) for c in l])
    
    print s
    
  • Same basic solution as others, but I personally prefer to use map instead of the list comprehension:

    
    >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
    >>> ''.join(map(chr,L))
    'hello, world'
    
  • import array
    def f7(list):
        return array.array('B', list).tostring()
    

    from Python Patterns - An Optimization Anecdote

    From Toni Ruža

0 comments:

Post a Comment