簡體   English   中英

Function 返回“無” Python

[英]Function return 'None' Python

嗨,我正在自己學習 python。

任務:在不影響特殊字符的情況下反轉單詞

示例 "abcd efgh" => "dcba hgfe" 示例 "a1bcd efg!h" => "d1cba hgf!e"

我的問題: function 返回無

然后我添加了這一行: return reverse_text但它仍然返回 None

誰能告訴我我的錯誤在哪里,好嗎?

我的代碼:

from string import punctuation
from string import digits


def reverse_text(str_smpl):
    sp = set.union(set(punctuation), set(digits))
    reverse_text.lst = []
    for word in str_smpl.split(' '):
        letters = [c for c in word if c not in sp]
        for c in word:
            if c not in sp:
                reverse_text.lst.append(letters.pop())
                continue
            else:
                reverse_text.lst.append(c)
        reverse_text.lst.append(' ')
    return reverse_text


if __name__ == '__main__':
    cases = [
        ("abcd efgh", "dcba hgfe"),
        ("a1bcd efg!h", "d1cba hgf!e"),
        ("", "")
    ]

    for text, reversed_text in cases:
        assert reverse_text(str_smpl) == reversed_text

    reverse_text(input('Input string '))
    print("".join(reverse_text.lst))

問題是您返回的reverse_text是 function 的名稱,因此 function 正在返回對自身的引用(不是您想要的。)。

像使用reverse_text.lst那樣為函數分配屬性並不是我在 Python 中真正遇到的事情,我建議您只使用一個名為reversed_text_list的新局部變量以避免混淆。

我認為您還想將列表中的字符連接在一起並返回一個字符串。

以下似乎正在做我認為你正在嘗試做的事情:

def reverse_text(str_smpl):
    sp = set.union(set(punctuation), set(digits))
    reversed_text_list = []
    for word in str_smpl.split(' '):
        letters = [c for c in word if c not in sp]
        for c in word:
            if c not in sp:
                reversed_text_list.append(letters.pop())
                continue
            else:
                reversed_text_list.append(c)
        reversed_text_list.append(' ')
        reversed_text = ''.join(reversed_text_list)
    return reversed_text

它返回錯誤,因為您定義了reverse_text.lst但僅返回reverse_text ,以下代碼將起作用:-

from string import punctuation
from string import digits


def reverse_text(str_smpl):
    sp = set.union(set(punctuation), set(digits))
    lst = []
    for word in str_smpl.split(' '):
        letters = [c for c in word if c not in sp]
        for c in word:
            if c not in sp:
                lst.append(letters.pop())
                continue
            else:
                lst.append(c)
        lst.append(' ')
    return "".join(lst)


if __name__ == '__main__':
    cases = [
        ("abcd efgh", "dcba hgfe"),
        ("a1bcd efg!h", "d1cba hgf!e"),
        ("", "")
    ]

    for text, reversed_text in cases:
        print(reverse_text(text))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM