2017-01-02 38 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)。 –