2

I am using pyinputplus and specifically inputNum https://pyinputplus.readthedocs.io/en/latest/

This is what my code looks like:

msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputNum(prompt=msg, allowRegexes=r'^[qQsS]$', blank=False)

My goal is to allow any number but also allow one of the following q,Q,s,S.

However when I run the code and enter 'sam' the code crashes because later on I am trying to convert to float(answer).

My expectation is that allowRegexes will not allow this and will show me the prompt again to re-enter. Please advise!

trustory
  • 215
  • 3
  • 13

1 Answers1

1

It seems pyip.inputNum stops validating the input if you provide allowRegexes argument. See the allowRegexes doesn't seem work properly Github issue.

You can use the inputCustom method with a custom validation method:

import pyinputplus as pyip
import ast

def is_numeric(x):
    try:
        number = ast.literal_eval(x)
    except:
        return False
    return isinstance(number, float) or isinstance(number, int)

def raiseIfInvalid(text):
    if not is_numeric(text) and not text.casefold() in ['s', 'q']:
        raise Exception('Input must be numeric or "q"/"s".')

msg = 'Enter value to add/replace or s to skip field or q to quit: '
answer = pyip.inputCustom(raiseIfInvalid, prompt=msg)

So, if the text is not and int or float and not equal to s/S/q/Q, the prompt will repeat showing up.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • thanks @Wiktor Stribizew. do you know how to check in the custom exception and allow floats. i believe isnumeric doesnt allow decimal points – trustory May 11 '21 at 18:27
  • @trustory There are a lot of such resources, see [Check if a number is int or float](https://stackoverflow.com/questions/4541155/check-if-a-number-is-int-or-float). [This answer](https://stackoverflow.com/a/4541207/3832970) may help. Or, check [this thread](https://stackoverflow.com/questions/59807810/how-to-check-if-input-is-float-or-int). – Wiktor Stribiżew May 11 '21 at 18:37
  • Stribizew would this work too? if not string.replace(",","").isnumeric() – trustory May 11 '21 at 20:28
  • 1
    @trustory I added the full code snippet. Does it work for you now? – Wiktor Stribiżew May 12 '21 at 08:31