I can accept user's input in two formats:
123
123,234,6028
I need to write a function/a few lines of code that check whether the input follows the correct format.
The rules:
- If a single number input, then it should be just a number between 1 and 5 digits long
- If more then one number, then it should be comma-separated values, but without spaces and letters and no comma/period/letter allowed after the last number.
The function just checks if formatting correct, else it prints Incorrect formatting, try entering again
.
I would assume I would need to use re
module.
Thanks in advance
CodePudding user response:
You can use a simple regex:
import re
validate = re.compile('\d (?:\.\d )?(?:,\d )*')
validate.fullmatch('123')
validate.fullmatch('123.45,678,90')
Use in a test:
if validate.fullmatch(your_string):
# do stuff
else:
print('Incorrect formatting, try entering again')
To also allow floats after the first comma: '\d (?:\.\d )?(?:,\d (?:\.\d )?)*')
CodePudding user response:
The following code should leave the Boolean variable valid
as True
if the entered ibnput complies with your rules and False
otherwise:
n = input("Your input: ")
valid = True
try:
if int(n) > 9999:
valid = False
except:
for character in n:
if not character in "0123456789,":
valid = False
if n[-1] == ",":
valid = False
CodePudding user response:
Another option is:
def validString(string):
if not all(
v.isdigit() for v in string.split(",") if 0 < len(v) < 6
):
print("Incorrect formatting, try entering again.")