So I have been struggling to find out what is wrong with my exception code which is to only accept strings but also display text whenever there are non string inputs between the brackets which depends on where I put the "try" and except functions.
The first code I have here which 'try' is before return, any strings entered in will be accepted into the function, however the except functions will not work whenever non-strings are entered between the bottom brackets.
''' def string_processor(string):
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA 1
try:
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except IndexError:
print("Please enter a string with quotation marks ")
else:
print("Please only enter a string")
string_processor("000")
'''
The second code I have which I put "try:" can sort out some things such as AttributeErrors, but only strings with letters can be inputted between the brackets and any string that contains non-numbers are omitted from the function.
'''
def string_processor(string):
try:
countA = 0
if (string.isalpha()):
for c in string:
if c == "a":
countA = countA 1
return countA / len(string)
except AttributeError:
print("Please enter a string instead")
except SyntaxError:
print("Please enter a string with quotation marks ")
else:
print("Please only put letters in your string")
string_processor("000")
'''
I request help to fix this problem so my program can get any type of string, and will process except functions for any non-string values.
CodePudding user response:
I could be wrong understanding your question. But here are my suggestions to solve your problem.
First of all, I couldn't understand your code because the else statement is not reachable there, so I slightly changed it, but nothing dramatically changed.
def string_processor(string):
# This is a bad way to check the types and the value
try:
if string.isalpha():
# If string has a type "string" and contains only letters
return string.count('a')/len(string)
elif string.isnumeric():
# If string has numbers only
print("Please enter a string instead")
except:
if isinstance(string, list):
# If type of the "string" is actually a list
print('This is not a string, this is a list')
elif type(string) == tuple:
# If type of the "string" is actually a tuple
print('This is not a string, this is a tuple')
else:
# If none of the above worked
print('It is definitely not a pure string')
a = string_processor(234)
As I commented, this is not a good way to implement the solution, the better way may be this:
def string_processor_another(value):
# It is better to RAISE exceptions, not to print them
if not isinstance(value, str):
raise TypeError('This must be a string')
# So if we come to this step we can be sure that we work with strings, so we can use the methods
if value.isalpha():
# If string has a type "string" and contains only letters
return value.count('a')/len(value)
elif value.isnumeric():
# If string has numbers only
print("Please enter a string instead")
b = string_processor_another(234)
And if you are going to add some extra logics or you want to have a cleaner code, I'd suggest you to make this in oop way
class StringProcessor:
def __init__(self, string):
self.__check_for_str(string)
self.string = string
@staticmethod
def __check_for_str(string):
return isinstance(string, str)
# Here you can add short functions to make all of your logic statements
def check_is_numeric(self):
print(self.string.isnumeric())
def check_is_alpha(self):
print(self.string.isalpha())
sp = StringProcessor('1234')
sp.check_is_numeric() # True
sp.check_is_alpha() # False
Hope it helped.