小编Mar*_*ita的帖子

为什么foo = filter(...)返回<filter object>,而不是列表?

在Python IDLE 3.5.0 shell中工作.根据我对内置"过滤器"函数的理解,它会返回列表,元组或字符串,具体取决于您传入的内容.那么,为什么下面的第一个分配工作,而不是第二个('>>>只是交互式Python提示)

>>> def greetings():
    return "hello"

>>> hesaid = greetings()
>>> print(hesaid)
hello
>>> 
>>> shesaid = filter(greetings(), ["hello", "goodbye"])
>>> print(shesaid)
<filter object at 0x02B8E410>
Run Code Online (Sandbox Code Playgroud)

python variables filter variable-assignment

55
推荐指数
3
解决办法
7万
查看次数

python - 最有效的代码来搜索和替换句子中的单词?

我正在一个在线Python课程中进行简单练习 - 一个名为"censor"的练习需要2个输入,一个句子和一个单词 - 然后返回句子,并将所有给定单词的实例替换为星号.每次替换中的星号数等于原始单词中的字符数.为简单起见,练习假定不需要输入错误检查.我的代码有效,但我想知道它是否可以提高效率?:

def censor(text, word):
    textList = text.split()
    for index, item in enumerate(textList):
        count = 0
        if item == word:
            for char in word:
                count += 1
            strikeout = "*" * count
            textList[index] = strikeout
            result = ' '.join(textList)
    return result
Run Code Online (Sandbox Code Playgroud)

python string replace character

1
推荐指数
1
解决办法
234
查看次数