Convert Letter to Number in Python

Convert Letter to Number in Python

  1. Use the ord() Function to Convert Letters to Numbers in Python
  2. Use list comprehension to Convert Letters to Numbers in Python

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 Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python
  • Related Article - Python Number

  • Create a List of Odd Numbers in Python
  • Display a Number With Leading Zeros in Python
  • Check if a Character Is a Number in Python
  • Implement the GCD Operation in Python
  • Find Number of Digits in a Number in Python