用';'执行在 python

exec with ';' in python

我正在创建一个字符串,用于打印列表中的字段,。字段应该用';'分隔,代码片段看起来像这样(简化代码,不是实际的)

list = ["abc","xyz","pqr"]
str = "print " +  "list[0]"  + ";" + "list[2]" # This is dynamically generated
exec (str)

我的问题是,使用 exec 语句,它只打印 "xyz" ,因为有分号。解决这个问题的最佳方法是什么,以便 exec 语句打印 "xyz;pqr"

试试这个:

str = "print" + "list[0]" + "';'" + "list[2]" 

str = "print" + "list[0]" + "/;" + "list[2]"

您正在生成以下代码:

print list[0];list[2]

请注意 ; 未引用。由于 Python 使用 ; 分隔一行中的多个简单语句,因此 Python 首先执行 print list[0],然后 list[2](最终什么都不做).

您必须改为生成此代码:

print list[0] + ';' + list[2]

你可以用来做什么:

str = "print " +  "list[0]"  + " + ';' + " + "list[2]"

但是,您根本不应该使用代码生成。使用标准 Python 方法连接或格式化字符串。你可以使用 str.format():

print '{};{}'.format(list[0], list[2])

或者您可以使用 str.join():

print ';'.join([list[0], list[2]])

如果您必须根据其他一些变量来改变执行的代码,请尽量避免 exec。您可以使用 from __future__ import print_function 或将 print 语句封装在一个新函数中,然后动态调用函数。例如,您始终可以使用 dispatch table 将字符串映射到要调用的函数。

这里的问题是 Python 可选地允许分号分隔两个单独的语句 (Compound statements)。因此,当您在评估语句 print "abc";"xyz" 上使用 exec 时,Python 认为它们是两个独立的语句,因此,仅 printing "abc".

您可以在分号周围使用单引号来表明它是一个字符串,并将它们与周围的字符串连接起来:

# Refrain from using list and str as they are built-ins
l = ["abc", "xyz", "pqr"]
s = "print " +  "l[0]"  + "+';'+" + "l[2]"
exec(s)