簡體   English   中英

Python用eval替換括號內的文本

[英]Python Replace text inside brackets with it's eval

我有一個文件(或字符串,如果需要的話),像這樣:

$((2+1))
bbb$((2+0))a()
$((1+1))$((5**2))
$((variable+1))

我希望輸出是這樣的(如果變量= 1):

3
bbb2a()
225
2

基本上,首先我需要在$((和))之間獲取文本,我可以這樣做:

re.search(rf"\$\(\((.*?)\)\)",template).group(1)

因此,我需要用上一步中得到的所有值替換所有發生的情況。 我該怎么做? 我可以以某種方式之前編譯正則表達式並將其用於獲取文本和替換文本嗎? 謝謝

您不需要使用任何庫。 您所需要的只是使用python內置函數。

m = ["$((2+1))","$((2+0))","$((1+1))aa$((5**2))bb","$((0+0))"]

def OPGetter(string) :
    i = 0
    while i < len(string) :
        if string[i] == ")" :
            last = i
        i += 1
    res1 = (string[last+1:])
    #
    i = 0
    while i < len(string) :
        if string[i] == "(" :
            one = i+1
        i += 1
    i = 0
    while i < len(string) :
        if string[i] == ")" :
            two = i
            break
        i += 1
    return [string[one:two],res1]

result =[]
i = 0
while i < len(m) :
    string = m[i].split("$")
    if len(string) > 0 :
        res = string[0]
        string = string[1:]
    for item in string :
        code = "def returning() :\n    return "+ OPGetter(item)[0]
        exec(code)
        value = returning()
        res += str(value)+OPGetter(item)[1]
    result.append(res)
    i += 1

結果將是答案的最終列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM