Write a Python function that validates a user input to be N digits separated by N-1 commas.

def check_input_format(user_input):
if not user_input:
return False
if not user_input[0].isnumeric() or not user_input[-1].isnumeric():
return False
input_list = user_input.split(“,”)
input_list = [int(x) for x in input_list]
except ValueError:
return False
if len(input_list) != len(set(input_list)):
return False
return True

The check_input_format(user_input) function takes in a user’s input as a string, and checks if it follows the specified format.

The function first checks if the input is empty or if the first and last characters are not numbers, and returns False in either case. This is done by using the not operator on the input string and checking if the first and last characters are numeric with the isnumeric() method.

Then it splits the input string by commas using split(“,”) method, converts the resulting list elements to integers using list comprehension, and checks if there are any duplicates using len(input_list) != len(set(input_list)). If there are duplicates it will return False.

If the input passes all the above checks, it will return True.

If the input is not formatted in the correct way or the conversion to int throws an error, the function returns False.


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *