user2325057 user2325057 - 6 months ago 10
Python Question

simplify code using a list in python

I have a line of python code that basically asigns a integer to a string (one letter). Since I use if statements, it need a lot of code lines... Is there a way I could simplify my code using a list so that it doesn't take up 63 lines of code? Here's my code:

if character in " ":
character = 0
elif character in "Aa":
character = 1
elif character in "Bb":
character = 2
elif character in "Cc":
character = 3
elif character in "Dd":
character = 4
elif character in "Ee":
character = 5
elif character in "Ff":
character = 6
elif character in "Gg":
character = 7
elif character in "Hh":
character = 8
elif character in "Ii":
character = 9
elif character in "Jj":
character = 10
elif character in "Kk":
character = 11
elif character in "Ll":
character = 12
elif character in "Mm":
character = 13
elif character in "Nn":
character = 14
elif character in "Oo":
character = 15
elif character in "Pp":
character = 16
elif character in "Qq":
character = 17
elif character in "Rr":
character = 18
elif character in "Ss":
character = 19
elif character in "Tt":
character = 20
elif character in "Uu":
character = 21
elif character in "Vv":
character = 22
elif character in "Ww":
character = 23
elif character in "Xx":
character = 24
elif character in "Yy":
character = 25
elif character in "Zz":
character = 26
elif character in ".":
character = 27
elif character in ",":
character = 28
elif character in "?":
character = 29
elif character in "'":
character = 30
else:
character = 0

Answer

Put all of the characters into one big string where the characters' positions in that string are the values you want to assign. You can handle upper and lowercase letters by converting the input to lowercase first.

value = " abcdefghijklmnopqrstuvwxyz.,?'".find(character.lower())