简体   繁体   English

如何找出放置“try”功能的问题?

[英]How do I figure out my issue with placing the "try" function?

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.所以我一直在努力找出我的异常代码有什么问题,即只接受字符串,但只要括号之间有非字符串输入,它也会显示文本,这取决于我放置“try”和 except 函数的位置。

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): ''' def string_processor(字符串):

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")字符串处理器(“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.我输入的第二个代码“try:”可以整理出一些东西,例如 AttributeErrors,但只能在括号之间输入带有字母的字符串,并且函数中省略了任何包含非数字的字符串。

''' def string_processor(string): ''' def string_processor(字符串):
try:尝试:
countA = 0 if (string.isalpha()): for c in string: if c == "a": countA = countA + 1 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")字符串处理器(“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.我请求帮助解决这个问题,以便我的程序可以获取任何类型的字符串,并将处理除函数之外的任何非字符串值。

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.首先,我无法理解您的代码,因为那里无法访问 else 语句,所以我稍微更改了它,但没有任何显着变化。

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如果您要添加一些额外的逻辑或者您想要更简洁的代码,我建议您以 oop 方式进行

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.希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我该如何解决? - How do I figure this out? 我的 fig1.savefig 函数将我的图形保存为空白屏幕,我该如何解决这个问题? - My fig1.savefig function is saving my figure as a blank screen, how do I fix this? 当我将Django应用程序从一个系统复制到另一个系统时,如何确定要安装哪些依赖项? - How do I figure out what dependencies to install when I copy my Django app from one system to another? 当我尝试将数据从 Google Search Console 提取到 BigQuery 时,如何阻止我的脚本超时? - How do I stop my script from timing out when I try to extract data from Google Search Console to BigQuery? 如何跳出 python 中的 try 循环? - How do I break out of a try loop in python? 使用 Python 3.7 和 Selenium,我不知道如何解决我的代码中的视口元素问题 - Using Python 3.7 and Selenium, I can't figure out how to troubleshoot my code for out of Viewport elements 我的二分查找函数返回 None,我不知道为什么 - My function for binary search returns None, I can't figure out why 如何找出struct.unpack的格式(因为我没有在Python中打包)? - How do I figure out the format for struct.unpack (because I didn't pack in Python)? 如何使用 try 语句优化我的代码? - How do I optimize my code with try statement? 我想弄清楚怎么做 - I want to figure out how to make t
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM