3

Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

string = input(“Enter a line of text: “) l = list(string) return(l) 

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

2
  • A string is already a collection of characters. No need for the second line. Commented Nov 13, 2017 at 19:55
  • 1
    Note: Assuming OP is using Python3 (notice input()), the result is a list of Unicode code points, not a list of ASCII values. Commented Nov 13, 2017 at 19:57

5 Answers 5

2

You might use a list comprehension, like so:

string = input(“Enter a line of text: “) list_of_characters = list(string) list_of_ord_values = [ord(character) for character in list_of_characters] 

Note that, since strings are iterable, you can skip the intermediate step:

list_of_ord_values = [ord(character) for character in string] 
Sign up to request clarification or add additional context in comments.

Comments

1
string = input("enter string: ") for i in string: if i != ' ': # ignoring space char print(i, ord(i)) 

Input

sample string 

Output

s 115 a 97 m 109 p 112 l 108 e 101 s 115 t 116 r 114 i 105 n 110 g 103 

The output can even be saved to another list.

Comments

0

You need to make a for loop to loop over each character and convert them to ASCII.

You already have l which is a list of each character in the string. So loop over l and convert each character in the list to the ASCII value using ord().

Comments

0

Here's a time complexity efficient way of doing it. Assuming your list is of single characters as such:

l = ['a', 'b', 'c'] ascii_values = map(ord, l)

This will map each character to its specified ascii value.

Comments

0

If you are using python 2, strings are encoded as ascii by default. If you are using python 3, you can convert a string to ascii using the built-in string method encode:

ascii = string.encode('ascii') 

If you want this to be represented as a list, you might try encoding each separately, as the default iterated representation for ascii characters are integers. (try [x for x in b'binary string!'])

ascii_chars = [char.encode('ascii') for char in string] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.