Python:使用ord中没有的find函数

2024-09-30 20:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,下面的代码获取一个输入信息字符串(一个数学表达式),并使用find函数来查找“*/+-”中的一个运算符,并相应地分隔字符串。你知道吗

def splitting1(z):
    for operators in "*/+-":
        if operators in z:
            position1= z.find(operators)
            position2= z.rfind(operators)
            text_before_operators= (z[:position1]).strip()
            text_after_operators= (z[(position1+1):(position2)]).strip()
            return text_before_operators,text_after_operators

我的问题是,如果我有一个输入表达式,比如3/5*7,那么position1将首先找到*,然后再找到/。我希望代码将“position1”与最左边的运算符相关联。在使用for/in函数时,有没有办法省略运算符的优先级?如果没有,是否有更好的字符串操纵器可以省略优先顺序。你知道吗

注z是输入。输入仅限于两个运算符,以防产生歧义。你知道吗


Tags: 函数字符串代码textinfor表达式运算符
2条回答

您正在迭代*/+-,因此找到的第一个字符就是返回的第一个字符。你知道吗

您基本上需要找到所有这些操作符的索引,然后找到最大或最小的。尝试重新编写此函数以适用于字符串的另一端:

def find_operator_right(text):
    position = -1

    for oper in '*/+-':
        index = text.rfind(oper)

        if index > position:
            position = index

    return position

一个稍微更具脓性的解决方案是这样的:

right_index = max(map(text.rfind, '+-/*'))

看起来您正在尝试lex,因此我建议您研究专门为此目的设计的模块,例如^{}。你知道吗

是的。你知道吗

尽管如此,我认为您在本例中的思路是正确的,但是您缺少了一些递归(为了使这些更通用的lexer):

def splitting1(z):
    for char in "*/+-":
        if char in z:
            position = z.find(char)
            text_before_operator= (z[:position]).strip()
            text_after_operator= (z[position+1:]).strip()
            return (char, splitting1(text_before_operator), splitting1(text_after_operator))
    return ("number", z)

找到最左边的运算符而不考虑其优先级(即省略运算符优先级)的一种方法是重新排列您迭代的内容:

def splitting2(z):
    for char in z:
        if char in "*/+-":
            position = z.find(char)
            text_before_operator= (z[:position]).strip()
            text_after_operator= (z[position+1:]).strip()
            return (char, splitting2(text_before_operator), splitting2(text_after_operator))
    return ("number", z)

注意,这些函数返回与原始函数不同的结果。

相关问题 更多 >