Linux (28) Python (13) Raspberry Pi (5) Bugs (3) Install (3) C (2) Brainf**k (1) HTML (1) Maths (1) Sorts (1)

Wednesday, 23 December 2015

How to get the ASCII values of a string in python

ASCII values are the codes that correspond to printable characters. In total there are 255 but only 127 of them are commonly used.You can look at the ASCII table here
You can also run man ascii to get the ASCII table.
Note: All of the code needs to be run in the python3 console
To get a value of a character in python run:

This should give you the result of 97.
To get the character of a ASCII value in python run:

This should give you the result of 'a'

These built in functions only take 1 argument so if we want to get the ASCII representation of a string then a for loop needs to be implemented.
This would look something like this:
word = input("Please enter a word: ")
for char in word:
If we run this with the word hello then we should get the result:

To store these values in a array this would be implemented by adding the following code.
word = input("Please enter a word: ")
char_array = []
for char in word:

If we run this code with the word hello we should get the result:
[104, 101, 108, 108, 111]

No comments:

Post a Comment