【问题标题】:Trouble returning variable in python function在 python 函数中返回变量时遇到问题
【发布时间】:2013-01-30 16:21:02
【问题描述】:

我只是想修改一个字符串并返回修改后的字符串,但是,在打印变量时我得到“无”返回。

def AddToListTwo(self,IndexPosition):
    filename = RemoveLeadingNums(self, str(self.listbox1.get(IndexPosition))) #get the filename, remove the leading numbers if there are any
    print filename #this prints None
    List2Contents = self.listbox2.get(0, END)
    if(filename not in List2Contents): #make sure the file isn't already in list 2
        self.listbox2.insert(0, filename)

def RemoveLeadingNums(self, words):
    if(isinstance(words,str)):
        match = re.search(r'^[0-9]*[.]',words)
        if match: #if there is a match, remove it, send it through to make sure there aren't repeating numbers
            RemoveLeadingNums(self, re.sub(r'^[0-9]*[.]',"",str(words)).lstrip())
        else:
            print words #this prints the value correctly
            return words
    if(isinstance(words,list)):
        print "list"

编辑 - 多人评论说如果有匹配项我不会返回值。如果有的话我不想退货。它可能会重复(例如:1.2. itema)。所以,我想基本上使用递归来删除它,然后返回值

【问题讨论】:

  • 这段代码看起来很多余。为什么RemoveLeadingNums 以递归开头?
  • 递归。该值可能是“1.2.4. item”,我想在 item 之前删除整组值。
  • 为了响应您的编辑,如果您不想在匹配时返回任何内容,请不要将结果分配给filename。这段代码没有意义。
  • 查看您的编辑 -- 我不确定您是否理解 re.sub 所做的 -- 或者您可能不了解字符串的不变性?我不确定,但在我看来你在这里遗漏了一些东西......
  • 我已经解释过你使用递归错误。我知道你认为你正在尝试做什么,但它不会起作用(更努力地思考递归将如何发挥作用)。阅读:mywiki.wooledge.org/XyProblem

标签: python function return


【解决方案1】:

RemoveLeadingNums 返回None 的情况有多种。例如如果采用if match: 分支。也许应该是:

if match: 
    return RemoveLeadingNums(...

如果您有任何不是传入字符串的数据类型,您也返回None

【讨论】:

    【解决方案2】:

    在匹配的情况下,您不会返回任何内容。应该是:

    return RemoveLeadingNums( ... )
    

    【讨论】:

    • 我做到了。现在它变得更没有意义了。没有返回,对 RemoveLeadingNums 的调用绝对没有,因为字符串没有改变。
    • 是的。 RemoveLeadingNums(self, re.sub(r'^[0-9]*[.]',"",str(words)).lstrip())
    • 那么,让我们将递归添加到您不了解的事物列表中。仅仅调用一个函数不会对调用函数中字符串的值做任何事情。 words 保持不变
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多