0

I can accept user's input in two formats:

  1. 123
  2. 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:

  1. If a single number input, then it should be just a number between 1 and 5 digits long
  2. 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

4
  • 2
    You could do it with re, but its simple enough that a more brute force solution with str.split, among other options. Its not going to be a big deal either way. If you like re, try an implementation and come back if you need specific help. Commented May 8, 2022 at 20:28
  • I have a doubt regarding your comment on "no dots" after the last number. Do you want to allow floats? How? Commented May 8, 2022 at 20:47
  • @mozway I would not want floats. Simply numbers (in my case they are IDs) separated by commas (if it's more than 1 number). Thank you for you answer. Could you do a minor correct so that input can be only from 1 to 5 digits long? Commented May 8, 2022 at 21:00
  • @Alex thanks for the feedback, I updated the answer to only allow numbers of 1 to 5 digits Commented May 9, 2022 at 4:51

3 Answers 3

2

You can use a simple regex:

import re

validate = re.compile('\d{1,5}(?:,\d{1,5})*')

validate.fullmatch('123') # valid

validate.fullmatch('123,456,789') # valid

validate.fullmatch('1234567') # invalid

Use in a test:

if validate.fullmatch(your_string):
    # do stuff
else:
    print('Incorrect formatting, try entering again')
Sign up to request clarification or add additional context in comments.

2 Comments

validate.fullmatch('1234567') matches, but shouldn't by rule 1.
@DarrylG I had misread, I updated
1

Another option is:

def validString(string):
    listofints = [v.isdigit() for v in string.split(",") if 0 < len(v) < 6]
    if not len(listofints) or not all(listofints):
        print("Incorrect formatting, try entering again.")

1 Comment

validString('1234567') should detect incorrect formatting, but doesn't.
0

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

1 Comment

For ,,0 valid is True but should be False.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.