2017-01-02 60 views
0

嘿!简单函数不返回字符串值

第一次在这里张贴问题,我通常通过搜索找到了答案,但这个时候,我来到了干。

我用Python写一个非常简单的功能,但它拒绝返回一个值。基本上你应该输入HTML代码,它会删除所有的HTML标签(通过搜索<和>,然后拼接一个新的字符串)。

def pretty_print(source_code): 
    article_nohtml = remove_html(source_code) 

    print(article_nohtml) 

def remove_html(article): 
    code_starts_at = article.find('<') 

    if code_starts_at != -1: 
     beginning_of_article = article[:code_starts_at] 
     code_ends_at = article.find('>')+1 
     end_of_article = article[code_ends_at:] 
     stitched_article = beginning_of_article + end_of_article 
     remove_html(stitched_article) 
    else: 
     print(type(article)) 
     print(article) 
     return article 

#Test the function 
remove_html('<p>This is a text to <strong> try the script out </strong></p>\n<p>Is this working for you?</p>') 

这段代码不包含任何非凡的东西,所以它是一个谜,为什么它不工作。我添加了最后两个打印调用来测试函数,它们返回类'str'和完整的字符串,看起来不错,但是当pretty_print函数应该打印文章时,它只输出None。

感谢所有帮助我能,这应该是简单的,但我可能失去了一些东西。

+0

'remove_html'只会在执行'else'分支时返回一个值。 – snakecharmerb

+1

你不会在'if'条件的第一部分返回任何东西。为什么不使用库(例如beautifulsoup)进行html解析? –

+0

@snakecharmerb确实如此,但当所有的代码都被删除后,else语句就会被执行。 –

回答

3

在你remove_html功能,内if你正在为remove_html(stitched_article)递归调用,但不必返回它的值(Python的需要为None)。将其更改为:

return remove_html(stitched_article) 
+0

谢谢,就像我认为这件事很简单。我完全忘记了递归过程是如何工作的。 :P –

+0

很高兴提供帮助。没必要说谢谢。如果这个答案有帮助,将其标记为[accepted](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –