How to Find an item’s Alphabet Position in Python

0 min read 117 words

The challenge

When provided with a letter, return its position in the alphabet.

Input :: “a”

Ouput :: “Position of alphabet: 1”

The solution in Python code

Option 1:

def position(alphabet):
    return "Position of alphabet: {}".format(ord(alphabet) - 96)

Option 2:

from string import ascii_lowercase
def position(char):
    return "Position of alphabet: {0}".format(
        ascii_lowercase.index(char) + 1)

Option 3:

def position(alphabet):
    return "Position of alphabet: %s" % ("abcdefghijklmnopqrstuvwxyz".find(alphabet) + 1)

Test cases to validate our solution

import test
from solution import position

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():

        tests = [
            # [input, expected]
            ["a", "Position of alphabet: 1"],
            ["z", "Position of alphabet: 26"],
            ["e", "Position of alphabet: 5"],
        ]
        
        for inp, exp in tests:
            test.assert_equals(position(inp), exp)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags