2016-11-17 14 views
0

我的代码在某些测试用例上返回一个异常,在其他测试用例上返回TRUE。如何在应用条件时替换字符串中的空格

CASE 1:

样本输入:

<br>source = 'Delhi'<br> 
destination = 'Agra'<br> 
Type = 'one-way' 

预期输出:

if exist -> return 'already exist' else: insert into dB. 

我的输出:

正常工作

案例2:

样品输入:

source = 'Delhi'<br> 
destination = 'A gra'<br> 
Type = 'one-way'<br> 

预期输出:

if exist -> return 'already exist' else: insert into dB. 

我的输出:

Error: local variable 'source' referenced before assignment 

如果我指定变量None它会展现成功者的成功等。

res = db.test("select source,destination,type from cities where source = '"+str(self.source)+"' and destination='"+str(self.destination)+"' and type = '"+str(self.type)+"'") 
for row in res: 
    source = row['source'] 
    destination = row['destination'] 
    types = row['type'] 
src = self.source 
dst = self.destination 
typ = self.type 
if str(src).replace(' ','').lower() == str(source).replace(' ','').lower() and str(dst).replace(' ','').lower() == str(destination).replace(' ','').lower() and str(typ).replace(' ','').lower() == str(types).replace(' ','').lower(): 
    return "already exist" 
+0

哪个例外?当你不给我们任何信息时,你如何期待我们帮助你解决错误 –

+0

向我们展示一个完整的追溯。你确定你的缩进是正确的吗? for循环只应该包含三行? –

+0

你称为**样本输入**是'res'的值?你能否提供它吗?你的代码是一个类的一部分。发布之前,您是否在课堂之外测试过它?你提供了输出和一个**类型的输入(如果'res'是输入,那么它是一个字典,一个列表,一个列表中的字典?一个字符串?......),但是你没有提供错误和一个体面的代码工作... –

回答

0

将循环外部的源变量,目标变量和类型变量初始化为空字符串。 您正尝试使用初始化并在for循环中声明的变量“source”。您必须在循环之外初始化它。

如果您仅在外部初始化“源”,则会在赋值之前引用第二个异常作为“局部变量”目标“。

source = "" 
destination = "" 
types = "" 
res = db.test("select source,destination,type from cities where source = '"+str(self.source)+"' and destination='"+str(self.destination)+"' and type = '"+str(self.type)+"'") 
for row in res: 
    source = row['source'] 
    destination = row['destination'] 
    types = row['type'] 
src = self.source 
dst = self.destination 
typ = self.type 
if str(src).replace(' ','').lower() == str(source).replace(' ','').lower() and str(dst).replace(' ','').lower() == str(destination).replace(' ','').lower() and str(typ).replace(' ','').lower() == str(types).replace(' ','').lower(): 
    return "already exist" 
+0

** Thankz ** sir :) –

0

正如其他人所建议的,请用stacktrace更新帖子,或者您尝试阅读错误,并且您将自己理解。我无法用代码,但2观测发现错误,

  1. 您使用的用户输入的同时生成一个查询(阅读有关SQL注入)使用查询参数,而不是

  2. 为什么你将每个变量转换为“str”?默认情况下,它应该是“str”

我想将此添加为评论,但没有代表添加评论。

+0

错误:在赋值之前引用局部变量'source' 如果我将变量赋值为None。然后它会显示不正确的成功。 –

+0

我把“str”,因为当我在这个特定的代码pycharm代码,它不显示替换()没有str。我不知道为什么。 –

+0

Python是鸭子打字,所以假设当代码执行时,它会发现替换.. pycharm没有显示,因为它不能从self.source或其他推断类型...你也可以检查是否所有的变量如果tyoe str。 .. isinstance(str,) –

相关问题