How to reduce similar python if statements?
I'm working on a project where I need to change numeric values ​​alphabetically, currently I have this:
if finposb == "2":
finposb = "a"
if finposb == "3":
finposb = "b"
if finposb == "4":
finposb = "c"
if finposb == "5":
finposb = "d"
if finposb == "6":
finposb = "e"
if finposb == "7":
finposb = "f"
if finposb == "8":
finposb = "g"
if finposb == "9":
finposb = "h"
I would like to know if there is a way to reduce this to a shorter line of code, thanks!
source to share
You don't need any intermediate data structures; use ASCII value (or Unicode code in Python 3) finposb
.
# ord("a") - ord("2") == 47
finposb = chr(ord(finposb) + 47)
If you don't have a good implicit rule like this, you can use string.maketrans
to make a translation table and string.translate
apply that table to your input.
>>> tbl = string.maketrans("23456789", "abcdefgh")
>>> string.translate("2", tbl)
'a'
translate
acts like an identification function if the first argument does not appear in the translation table:
>>> string.translate("z", tbl)
'z'
source to share
In this case, the dictionary is what you are looking for.
finposb = {
"2": "a",
...
"9": "h"
}
>>> print(finposb["2"])
a
Dictionary advantage is that you can map multiple keys with the same value, for example, if you want both "2"
, and 2
displayed in "a"
, you could say
finposb["2"] = "a" # string
finposb[2] = "a" # numeric
In addition, there are two reasonable ways to get your value from the key (for example, from "2" to "a").
finposb[key] # raise KeyError if key is not in the dictionary
finposb.get(key, None) # default to None if the key is missing
The former is convenient because it generates a useful error and can be sure that the key is not in your dictionary, while the latter has many other conveniences, such as the ability to return itself if the key is missing.
finposb.get(key, key) # returns key if key does not map to a value
Classically, this type of table is used to search for a character set such as ASCII , where many characters can be stored in a compact way (how else could you express a letter on a computer than as a number?) And then be interpreted by a program.
A more modern form of this is called unicode , which can be used to describe a very large number of different characters outside of the "normal" Latin alphabet.
source to share
>>> pool = {"2": "a", "3": "b", "4": "c", "5": "d", "6": "e", "7": "f", "8": "g", "9": "h"}
>>> finposb = '2' # get any digit here
>>> if str(finposb) in pool.keys():
finposb = pool[str(finposb)]
>>> finposb
'a'
if you use numbers as a string in a dictionary and then represent it as a string throughout the snippet.
source to share