简体   繁体   中英

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:

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. You should try to return data at the end of your function and then assign its value to output, such as:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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