Python - How To Convert Letter to Number in Python

ID : 43

viewed : 129

Tags : PythonPython StringPython Number

vote vote

100

This tutorial demonstrates the different ways available to convert letters to numbers in Python.

First, let us explain how converting a letter of the alphabet to a number is possible.

The term ASCII, an acronym for American Standard Code for Information Interchange, is essentially a standard capable of assigning letters, numbers, and some other characters in the 8-bit code that contains a maximum of 256 available slots.

Each character, no matter if it is a digit (0-9) or a letter (a-z) or (A-Z) has an ASCII value assigned to it, which can simply be utilized to figure out the number or the value that any letter of the alphabet holds.

To explain this tutorial, we will take a string of letters of the alphabet and convert it to a list of numbers.

Use the ord() Function to Convert Letters to Numbers in Python

The ord() function in Python is utilized to return the Unicode, or in this case, the ASCII value of a given letter of the alphabet. We will apply the ord() function to the letters and subtract 96 to get the accurate ASCII value.

The following code uses the ord() function to convert letters to numbers in Python.

l = "web" n = [] for x in l:    n.append(ord(x) - 96) print(n) 

The above code provides the following output:

[23, 5, 2] 

Use list comprehension to Convert Letters to Numbers in Python

List comprehension is a comparatively shorter and refined way to create lists that are to be formed based on the values given of an already existing list.

The code can pretty much be finished with a one-liner by using list comprehension here.

The following code uses list comprehension to convert letters to numbers in Python.

l = "web" n = [ord(x) - 96 for x in l] print(n) 

The above code provides the following output:

[23, 5, 2] 

  • Related HOW TO?