在python中将字符串正确地传递给eval()

2024-09-24 02:23:45 发布

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

我的问题是如何评估一个包含可信用户输入的字符串。我不知道如何正确打包字符串(try后的第一行:)。在下面的示例中,eval()出现异常。任何帮助都将不胜感激。下面是一个示例代码:

import ast

def do_set_operation_on_testids_file(str_filename1, str_filename2, str_set_operation):
  resulting_set = None
    with open(str_filename1) as fid1:
      with open(str_filename2) as fid2:
        list1 = fid1.readlines()
        list2 = fid2.readlines()

        try:
            str_complete_command = "set(list1)." + str_set_operation + "(set(list2))"
            resulting_set = ast.literal_eval(str_complete_command)
            for each_line in resulting_set:
                print(each_line.strip().strip('\n'))
        except:
            print('Invalid set operation provided: ' + str_set_operation)

非常感谢!你知道吗


Tags: 字符串示例aswithevalopenastoperation
1条回答
网友
1楼 · 发布于 2024-09-24 02:23:45

您根本不需要使用literal_eval()eval()。你知道吗

使用^{}按字符串获取set操作方法:

>>> list1 = [1,2,3,2,4]
>>> list2 = [2,4,5,4]
>>> str_set_operation = "intersection"
>>> set1 = set(list1)
>>> set2 = set(list2)
>>> getattr(set1, str_set_operation)(set2)
set([2, 4])

或者,可以传递一个^{}函数,而不是一个具有set方法名的字符串。示例:

>>> import operator
>>> def do_set_operation_on_sets(set1, set2, f):
...     return f(set1, set2)
... 
>>> do_set_operation_on_sets(set1, set2, operator.and_)
set([2, 4])

其中and_将调用set1 & set2,这是集合的交集。你知道吗

相关问题 更多 >