7

I have a flag in a Python program which can only be certain strings, rock, paper, or scissors. Python argparse has a great way to implement this, using choices, container of the allowable values for the argument.

Here's an example from the documentation:

import argparse
...
parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
parser.parse_args(['rock'])
### Namespace(move='rock')
parser.parse_args(['fire'])
### usage: game.py [-h] {rock,paper,scissors}
### game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors')

I would like to implement choices such that the choices are not case-sensitive, i.e. users could input RoCK and it would still be valid.

What is the standard way to do this?

ShanZhengYang
  • 16,511
  • 49
  • 132
  • 234

1 Answers1

23

You can set type=str.lower.

See Case insensitive argparse choices

import argparse

parser = argparse.ArgumentParser(prog='game.py')
parser.add_argument('move', choices=['rock', 'paper', 'scissors'], type=str.lower)
parser.parse_args(['rOCk'])
# Namespace(move='rock')
KPLauritzen
  • 1,719
  • 13
  • 23