Skip to content

How to Find an item’s Alphabet Position in Python

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)
Code language: Python (python)

Option 2:

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

Option 3:

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

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)
Code language: Python (python)

See also  Hamming Numbers in Java
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x