使用存储在字典中的多个定界符拆分字符串

Split string with multiple delimiters stored in a dictionary

我必须使用存储在 python 字典中的多个定界符来拆分字符串。

例如,这是我的带分隔符的字典:

import operator

ops = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv
}

这是字符串的示例:

mystring = "2 * 3 + 4 + 5  / (9 + 5)"

结果应该是:

result = ['2', '3', '4', '5', '(9', '5)']

是否可以只使用变量 'mystring' 和 'ops' 以及一些函数来做到这一点,而无需将所有分隔符字符串硬编码为函数参数?

您可以使用正则表达式为您解决这个问题。

r = re.compile('\(?\d+\)?')  # possible parenthesis surrounding an integer
r.findall(mystring)  

> ['2', '3', '4', '5', '(9', '5)']

如果您只想拆分任何非数字字符,请使用:

import re
a = "(20 * 20 / 19 - 29) ** 2"
out_list = re.findall(r"[\d']+", a)

如果您想进行实际计算,请说:

eval("(20 * 20 / 19 - 29) ** 2")

这可能有帮助:

import operator

ops = {"+": operator.add,
       "-": operator.sub,
       "*": operator.mul,
       "/": operator.truediv
       }

myString = "2 * 3 + 4 + 5 / (9 + 5)"


def getSubStrings(myInputString, delimiters):
    allSubStrings = [myInputString]

    tempList = []
    for eachKey in delimiters.keys():
        for eachSubString in allSubStrings:
            tempList += eachSubString.split(eachKey)
        allSubStrings = tempList
        tempList = []

    allSubStrings = [eachSubString.strip() for eachSubString in allSubStrings]

    return allSubStrings


print(getSubStrings(myString, ops))

给定字符串的答案是:

['2', '3', '4', '5', '(9', '5)']