Accept lowercase or uppercase letter in Python

Work with the menu display, where the letter "m" returns the user to the main menu. How can I get it so that it works whether the letter "m" is a lowercase or lowercase letter?

elif choice == "m": 
+4
source share
3 answers

One of

 elif choice in ("m", "M"): 
 elif choice in "mM": # false positive if choice == '' 
 elif choice == 'm' or choice == 'M': 
 elif choice.lower() == 'm': 

In terms of maintainability, the fourth alternative is better if you want to switch to case-insensitive comparison of multi-letter strings, since you need to provide all 2 N features in the 1st and 3rd alternatives. The second option only works for single-character strings.

With the 4th alternative it is also impossible to miss the case when you want to change 'm' to other letters.

In terms of efficiency, the second alternative is the most effective, and then the first, then the third and, finally, the fourth. This is due to the fact that the 3rd alternative includes more operations; and while calling functions and getting attribution is slow in Python, both make the 4th alternative relatively slow.

See http://pastie.org/1230957 for a disassembly and timeit result.

Of course, if you do not make this comparison 10 million times, there is no difference between each.

+12
source
 elif choice.lower() == "m": 
+7
source

This method would be explicit and very concise:

  elif choice in {'m', 'M'}: 

Of course, to express this, it requires Python 2.7 or 3.x, which support a set of literals . I don’t know how he compares efficiency with other answers, but doubt that it is important for such a case.

+1
source

All Articles