Home > database >  Given a character of the alphabet I want to compute and print an integer value as a result
Given a character of the alphabet I want to compute and print an integer value as a result

Time:12-06

Alphabet combines alphabet in lower case and upper case : ab...zAB...Z

If input character is 'a' expected result is 1.

If input character is 'b' expected result is 2.

If input character is 'z' expected result is 26.

If input character is 'A' expected result is 27.

If input character is 'B' expected result is 28.

If input character is 'Z' expected result is 52.

I've tried the above code that works but I wonder if a simplest solution exists.

c = input()
if "a" <= c <= "z":
   print (ord(c)-ord("a") 1)
elif "A" <= c <= "Z":
    print (ord(c)-ord("A") 27)

CodePudding user response:

You can use ascii_letters provided by the string module which consists of the lower-case alphabet followed by the upper-case alphabet and find the index of your letter.

from string import ascii_letters

c = input()
print(ascii_letters.index(c) 1)

You could even prepare the "lookup table" with a first unused character, that will avoid to add 1 when calling index().

from string import ascii_letters

table = "."   ascii_letters
c = input()
print(table.index(c))

CodePudding user response:

use the isupper() and islower() methods to check if character is upper or lower

c = input()
if c.islower():
    print(ord(c)-ord('a') 1)
elif c.isupper():
    print(ord(c)-ord('A') 27)
  • Related