简体   繁体   English

为什么这个 for 循环有效,而 function 无效?

[英]Why does this for loop work and the function doesn't?

Can anyone explain to me why this code works:谁能向我解释为什么这段代码有效:

data = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch,"")
print(data)

But when i try to create a function to do the same with this code, the output i get is None:但是当我尝试创建一个 function 来对这段代码做同样的事情时,我得到的 output 是无:

def clean(data):
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch," ")
bob = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
print(bob)
output = clean(bob)
print(output)

when you pass data as a parameter to your function and declare data = data.replace(ch, "") , you are modifying the parameter, not the original data passed to the function.当您将数据作为参数传递给 function 并声明data = data.replace(ch, "")时,您正在修改参数,而不是传递给 function 的原始数据。 You should try to return data at the end of your function and then assign its value to output, such as:您应该尝试在 function 末尾return data ,然后将其值分配给 output,例如:

def clean(data):
chars = "()[]?+"
for ch in chars:
    if ch in data:
        data = data.replace(ch," ")
return data
bob = "8 (including George Blake, aged 69, and Robert Reynolds, aged 12)"
print(bob)
output = clean(bob)
print(output)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM