[英]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.