简体   繁体   English

该代码在 function 之外工作正常,但一旦进入内部,它就不起作用

[英]The code works fine outside the function but once inside, it doesn't work

punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']


def strip_punctuation(word):

    for i in punctuation_chars:
        if i in word:
            word = word.replace(i, '')
            return word

print(strip_punctuation('GH.GH,GHGH:GHGH;GHGHG@'))

You're returning word after checking the first item, which means only the first punctuation mark ' would be stripped.您在检查第一项后返回word ,这意味着只有第一个标点符号'会被删除。 Replace the function with this.用这个替换 function。

def strip_punctuation(word):
    for i in punctuation_chars:
        if i in word:
            word = word.replace(i, '')
    return word

It's because the return is inside of one of the loops, so you only get the first iteration done before printing the returned value.这是因为返回是在其中一个循环内,所以你只能在打印返回值之前完成第一次迭代。 You'd need to put the return at the base of the function - out of the loops.您需要将返回放在 function 的底部 - 不在循环中。

def strip_punctuation(word):
    for i in punctuation_chars:
        if i in word:
            word = word.replace(i, '')
    return word

When you call return, the function is exited.当您调用 return 时,function 将退出。 Therefore, the first time that i is in word and you replace it, you return the word and the function exits.因此,第一次 i 在 word 中并替换它时,您返回 word 并且 function 退出。 If you were to complete the loop and then return the word, then it should work.如果您要完成循环然后返回单词,那么它应该可以工作。

ie IE

def strip_punctuation(word):
    for i in punctuation_chars:
        if i in word:
           word = word.replace(i, '')
    return word

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python代码在函数外部起作用,但在函数内部不起作用 - Python code works outside function, but doesn't work inside function Azure function 用 Python 在 VS Code 中编写,在本地测试中工作正常,但在 Azure 环境中不起作用 - Azure function written in Python in VS Code works fine on local test but doesn't work on Azure environment 尝试除了在 function 内不起作用但在外面 - Try except inside a function doesn't work but outside does For 循环在函数外工作正常,但在函数内抛出错误 - For loop works fine outside of function but throws error inside of function 代码在函数外部起作用,但在函数内部不起作用(Python) - Code works outside function, but not inside function (python) python代码在函数外工作,但不在函数内 - python code works outside the function but not inside function 我的代码在 function 之外有效,但在内部无效 - My code works outside the function but not inside 在列表中查找频率的代码。 计数为 function 的第二个代码工作得很好,但是使用循环的第一个方法不起作用,为什么? - Code to find frequency in a list. The 2nd code the one with the count function works just fine, but 1st method using loops doesn't work, why? 在我的PC上正常工作的Python代码在我的Raspberry Pi上不起作用 - Python code that works fine on my PC doesn't work on my Raspberry Pi 当我隔离到包中时,python代码不起作用 在同一文件中工作正常 - python code doesn't work when I segregate into packages | works fine in same file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM