You can use a list comprehension:
>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
Answer from Mark Byers on Stack OverflowYou can use a list comprehension:
>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
Here is a pretty concise way to perform the concatenation:
>>> s = "hello world"
>>> ''.join(str(ord(c)) for c in s)
'10410110810811132119111114108100'
And a sort of fun alternative:
>>> '%d'*len(s) % tuple(map(ord, s))
'10410110810811132119111114108100'
How do I convert a list of ascii values to a string in python? - Stack Overflow
Converting String Into Byte Array In ASCII Presentation
How do I "Convert Ascii Text to HTML Character Entities"
How to take inputs from an ascii file in Python
Videos
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'
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'
» pip install art
Hello everyone!
I am trying to convert a string into a byte array. If I for example use the string 'Hello' I want to get something like this to store it in a byte array variable:
b'\x48\x45\x4C\x4C\x4F'
What I tried is following:
buf = bytearray(50) # length of text string varies, so I reserved a buffer for a max length of 50 chars
char_arr = [char for char in text]
for i in range(0, len(char_arr)):
buf[i] = hex(ord(char_arr[i]))
This could possibly be total nonsense and I feel like I am making things way too complicated. The variable "text" is the string i read from. I tried converting the string into a char array to read it into the byte array. While doing that I used hex(ord()) to convert the char into its hexadecimal ASCII representation. I just started programming in this language to use CircuitPython on my Raspberry Pi Pico. I get an error called "can't convert str to int". Any suggestions? Thanks in advance!