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?


Asked by: Sophia337 | Posted: 24-09-2021






Answer 1

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'

Answered by: Marcus829 | Posted: 25-10-2021



Answer 2

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'

Answered by: Chelsea936 | Posted: 25-10-2021



Answer 3

import array
def f7(list):
    return array.array('B', list).tostring()

from Python Patterns - An Optimization Anecdote

Answered by: Julia250 | Posted: 25-10-2021



Answer 4

l = [83, 84, 65, 67, 75]

s = "".join([chr(c) for c in l])

print s

Answered by: Ted302 | Posted: 25-10-2021



Answer 5

You can use bytes(list).decode() to do this - and list(string.encode()) to get the values back.

Answered by: Gianna693 | Posted: 25-10-2021



Answer 6

Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:

charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
    mystring = mystring + chr(char)
print mystring

Answered by: Kate555 | Posted: 25-10-2021



Answer 7

def working_ascii():
    """
        G    r   e    e    t    i     n   g    s    !
        71, 114, 101, 101, 116, 105, 110, 103, 115, 33
    """

    hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
    pmsg = ''.join(chr(i) for i in hello)
    print(pmsg)

    for i in range(33, 256):
        print(" ascii: {0} char: {1}".format(i, chr(i)))

working_ascii()

Answered by: Patrick631 | Posted: 25-10-2021



Answer 8

I've timed the existing answers. Code to reproduce is below. TLDR is that bytes(seq).decode() is by far the fastest. Results here:

 test_bytes_decode : 12.8046 μs/rep
     test_join_map : 62.1697 μs/rep
test_array_library : 63.7088 μs/rep
    test_join_list : 112.021 μs/rep
test_join_iterator : 171.331 μs/rep
    test_naive_add : 286.632 μs/rep

Setup was CPython 3.8.2 (32-bit), Windows 10, i7-2600 3.4GHz

Interesting observations:

  • The "official" fastest answer (as reposted by Toni Ruža) is now out of date for Python 3, but once fixed is still basically tied for second place
  • Joining a mapped sequence is almost twice as fast as a list comprehension
  • The list comprehension is faster than its non-list counterpart

Code to reproduce is here:

import array, string, timeit, random
from collections import namedtuple

# Thomas Wouters (https://stackoverflow.com/a/180615/13528444)
def test_join_iterator(seq):
    return ''.join(chr(c) for c in seq)

# community wiki (https://stackoverflow.com/a/181057/13528444)
def test_join_map(seq):
    return ''.join(map(chr, seq))

# Thomas Vander Stichele (https://stackoverflow.com/a/180617/13528444)
def test_join_list(seq):
    return ''.join([chr(c) for c in seq])

# Toni Ruža (https://stackoverflow.com/a/184708/13528444)
# Also from https://www.python.org/doc/essays/list2str/
def test_array_library(seq):
    return array.array('b', seq).tobytes().decode()  # Updated from tostring() for Python 3

# David White (https://stackoverflow.com/a/34246694/13528444)
def test_naive_add(seq):
    output = ''
    for c in seq:
        output += chr(c)
    return output

# Timo Herngreen (https://stackoverflow.com/a/55509509/13528444)
def test_bytes_decode(seq):
    return bytes(seq).decode()

RESULT = ''.join(random.choices(string.printable, None, k=1000))
INT_SEQ = [ord(c) for c in RESULT]
REPS=10000

if __name__ == '__main__':
    tests = {
        name: test
        for (name, test) in globals().items()
        if name.startswith('test_')
    }

    Result = namedtuple('Result', ['name', 'passed', 'time', 'reps'])
    results = [
        Result(
            name=name,
            passed=test(INT_SEQ) == RESULT,
            time=timeit.Timer(
                stmt=f'{name}(INT_SEQ)',
                setup=f'from __main__ import INT_SEQ, {name}'
                ).timeit(REPS) / REPS,
            reps=REPS)
        for name, test in tests.items()
    ]
    results.sort(key=lambda r: r.time if r.passed else float('inf'))

    def seconds_per_rep(secs):
        (unit, amount) = (
            ('s', secs) if secs > 1
            else ('ms', secs * 10 ** 3) if secs > (10 ** -3)
            else ('μs', secs * 10 ** 6) if secs > (10 ** -6)
            else ('ns', secs * 10 ** 9))
        return f'{amount:.6} {unit}/rep'

    max_name_length = max(len(name) for name in tests)
    for r in results:
        print(
            r.name.rjust(max_name_length),
            ':',
            'failed' if not r.passed else seconds_per_rep(r.time))

Answered by: Lucas787 | Posted: 25-10-2021



Answer 9

Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))

Answered by: Edgar358 | Posted: 25-10-2021



Similar questions

how to convert list of hex values into hex string in Python?

hex_list = ['0x1', '0x17', '0x20', '0x19', '0x9'] I need to convert the hex list values in to hex string as it is given below: hexStr = '0117201909' Can some one please let me know how to do it in Python?


How to convert list of Hex values into Ascii string in python?

I have a list of Hex value variables in my python code. I need to convert into ASCII string. Can someone please suggest to me, how to convert it? HexList = ['0x0', '0x30', '0x32', '0x31', '0x30', '0x42', '0x32', '0x33', '0x38', '0x30', '0x30', '0x30', '0x31', '0x30', '0x32','0x43','0x30'] Expected value of Ascii string after the conversion= 0210B238000102C0


how to convert values of list of list to int in python 2.7

I have a list of list, such as T =[[0.10113], [0.56325], [0.02563], [0.09602], [0.06406], [0.04807]] I would like to find the total sum of these numbers. I am new to python programming, when I try a simple int(T[1]) conversion, I get error TypeError: int() argument must be a string or a number, not 'list' I appreciate any input.


file - Convert CSV to txt and start new line every 10 values using Python

I have a csv file with an array of values 324 rows and 495 columns. All the values for each row and col are the same. I need to have this array split up so that every 10 values is put in a new row. So for each of the 324 rows, there will be 49 full columns with 10 values and 1 column with 5 values (495 col / 10 values = 49 new rows with 10 values and 1 new row with 5 values). Then go to the next row and so on for 3...


how to convert text values in an array to float and add in python

i have a text file containing the values: 120 25 50 149 33 50 095 41 50 093 05 50 081 11 50 i extracted the values in the first column and put then into an array: adjusted how do i convert the values from text to float and add 5 to each of them using a for loop? my desired output is : 125 154 100 098 086


Convert XML into Lists of Tags and Values with Python

I'm learning Python and I'm trying to extract lists of all tags and corresponding values from any XML file. This is my code so far. def ParseXml(XmlFile): try: parser = etree.XMLParser(remove_blank_text=True, compact=True) tree = ET.parse(XmlFile, parser) root = tree.getroot() ListOfTags, ListOfValues, ListOfAttribs = [], [], [] for elem in root.iter('*'): ...


How to convert list of hex values into a byte array in python

This question already has answers here:


svm - Convert data values from Python to C

For this project I am working with libsvm. I have a python file that is able to output a list of feature vectors and I have a C executable that takes 2 csv files, a list of feature vectors and the svm model, as arguments and outputs a prediction in the form of a csv file. Now, I would like to change the C file such that it takes in the list output from the python file as its input arguments to make a pred...


how to convert list of hex values into hex string in Python?

hex_list = ['0x1', '0x17', '0x20', '0x19', '0x9'] I need to convert the hex list values in to hex string as it is given below: hexStr = '0117201909' Can some one please let me know how to do it in Python?


How to convert list of Hex values into Ascii string in python?

I have a list of Hex value variables in my python code. I need to convert into ASCII string. Can someone please suggest to me, how to convert it? HexList = ['0x0', '0x30', '0x32', '0x31', '0x30', '0x42', '0x32', '0x33', '0x38', '0x30', '0x30', '0x30', '0x31', '0x30', '0x32','0x43','0x30'] Expected value of Ascii string after the conversion= 0210B238000102C0


How to convert values in place in a python for loop?

In this simple python example: arr = [1,2,3,4,5] for n in arr: s = str(n) print(s) What I want to write is a code somehow similar to [str(n) for n in arr] but in the following format: arr = [1,2,3,4,5] for str(n) as s in arr: print(s) I basically want to include s=str(s) inside for statement. Is the ...


convert .txt values to lists in a Python script

Imagine we have a .txt file named a.txt and it has below lines. 1, 1, 3, 2, 1, 3,0 20, 30, 40, 20, 35, 34,0 Oct1,Nov1,Dec1 now we have a python project where I am going to read above line and assign different lines in different variables in a list format. ex: I need to assign as below var1=[1, 1, 3, 2, 1, 3,0] var2=[20, 30, 40, 20, 35, 34,0] var3=["Oct1","Nov1","De...


python - How to convert local time string to UTC?

How do I convert a datetime string in local time to a string in UTC time? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. Clarification: For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time:


How can I convert XML into a Python object?

I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: <main> <object1 attr="name">content</object> </main> And turn it into something like this: main main.object1 = "content" main.object1.attr = "name" The XML data will have a more complicated structure than that and I...


python - using jython and open office 2.4 to convert docs to pdf

I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno. This also means that my conversion c...


python - Convert a string with date and time to a date

This question already has answers here:


How to convert XML to JSON in Python?

This question already has answers here:


How do I convert part of a python tuple (byte array) into an integer

I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values: response = (0, 0, 117, 143, 6) The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used. I can access the tuple as response[0] but cannot see how I can get the firs...


python - How to convert a string of bytes into an int?

How can I convert a string of bytes into an int in python? Say like this: 'y\xcc\xa6\xbb' I came up with a clever/stupid way of doing it: sum(ord(c) << (i * 8) for i, c in enumerate('y\xcc\xa6\xbb'[::-1])) I know there has to be something builtin or in the standard library that does this more simply... This is different from


python - Convert number to binary string

Is this the best way to convert a Python number to a hex string? number = 123456789 hex(number)[2:-1].decode('hex') Sometimes it doesn't work and complains about Odd-length string when you do 1234567890. Clarification: I am going from int to hex. Also, I need it to be escaped. IE: 1234567890 -> '\x49\x96\x02\xd2' not '499602D2' Also, it needs to be ...


How do I convert a string to a double in Python?

I would like to know how to convert a string containing digits to a double.


python - Convert list of ints to one number?

I have a list of integers that I would like to convert to one number like: numList = [1, 2, 3] num = magic(numList) print num, type(num) >>> 123, <type 'int'> What is the best way to implement the magic function? EDIT I did find this, but it seem...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top