Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中呈现字符串时处理错误_Python_String_Render - Fatal编程技术网

在Python中呈现字符串时处理错误

在Python中呈现字符串时处理错误,python,string,render,Python,String,Render,在Python中呈现字符串时,我一直在处理错误。 为了清楚起见,我将举一个例子。 我在Python中有一个模板字符串,如下所示: template = "%(name)s, %(address)s, %(school)s" 我有一本字典如下: arg = {'name': nameString, 'address': addressString, } 使用以下命令呈现字符串时: myFinalStr = template%arg 这是一个错误: Tracebac

在Python中呈现字符串时,我一直在处理错误。 为了清楚起见,我将举一个例子。 我在Python中有一个模板字符串,如下所示:

template = "%(name)s, %(address)s, %(school)s"
我有一本字典如下:

arg = {'name': nameString,
       'address': addressString,
       }
使用以下命令呈现字符串时:

myFinalStr = template%arg
这是一个错误:

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'school'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
关键错误:“学校”

这是因为在模板字符串中找不到字段“school”。我如何处理这个错误(我不能使用try异常来处理,因为我认为它不是异常)


我必须处理此错误,因为我允许用户输入模板,模板可以是对的,也可以是错的。

您可以使用
try…除了

基本格式是

try:
   myFinalStr = template%arg
except KeyError:
   #do somthing to handle the keyerror
或者

try:
    template = "%(name)s, %(address)s, %(school)s"
    myFinalStr = template%arg
except KeyError:
     template = "%(name)s, %(address)s"
     myFinalStr = template%arg

这将处理错误。

“因为它不是异常”,它是异常。这是一个