Home > other >  How to raise an exception when a string isn't comma-separated
How to raise an exception when a string isn't comma-separated

Time:04-12

I want it to raise an exception and print Invalid input if the input string is not separated by commas. However, this is not raising an exception.

try:
    strings = [x for x in input().split(", ")]

except Exception:
    print("Invalid input.")

How can I raise an exception if the separator (i.e. comma) isn't present in the string?

CodePudding user response:

split() will return a list containing the original string if the delimiter doesn't appear in the list.

You can check the length of the resulting list -- if there's only one string, then the delimiter wasn't present in the original string, and you can raise an exception yourself:

strings = input().split(", ")
if len(strings) == 1:
    raise ValueError("Invalid input.")

I also got rid of the list comprehension in the assignment to strings -- .split() already returns a list, so it isn't necessary.

CodePudding user response:

Following code while check if all the words in the string are comma separated

import re

def check_comma_sepration(text_string):
    #Check if all the words in the string are seperated by comma
    word_count = len(re.findall(r'\w ', text_string))
    comma_sep_count = len(text_string.split(","))

    if word_count == comma_sep_count:
        print("Input string is comma separated ")
    else:
        print("Invalid input.")

#  ve test case
case1 = "Hi,this,is,case,one"
print("Case 1:")
check_comma_sepration(case1)
print()

# -ve test case
case2 = "Hi,this is case two"
print("Case 2:")
check_comma_sepration(case2)

# Output :
#     Case 1:
#     Input string is comma separated

#     Case 2:
#     Invalid input.

If this answer your query please upvote

  • Related