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)
CodePudding user response:
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)