'How to raise an exception when a string isn't comma-separated
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
There isn't any exceptional behavior in your code since (at least as what you expected) since split()
works just fine even if your delimiter is not found in the given string. It will just return the original string.
If all you want is to print a message if the input is not valid (i.e. not comma delimited), you can just check the split()
's return value:
strings = input().split(", ")
if len(strings) == 1:
print("Invalid input.")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BrokenBenchmark |
Solution 2 | halfer |
Solution 3 | Alcher |