我的问题是如何评估一个包含可信用户输入的字符串。我不知道如何正确打包字符串(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)
非常感谢!你知道吗
您根本不需要使用
literal_eval()
或eval()
。你知道吗使用^{} 按字符串获取set操作方法:
或者,可以传递一个^{} 函数,而不是一个具有set方法名的字符串。示例:
其中
and_
将调用set1 & set2
,这是集合的交集。你知道吗相关问题 更多 >
编程相关推荐