tlre0952b
tlre0952b

Reputation: 751

Why does this for loop have no effect? (Python)

I have a variable that contains a city, or city plus punctuation and then Post Code. I am using a statement to remove punctuation (and other stray) characters. It looks like this:

for c in "!@#%&*()[]{}/?<>,.":
    jobLocationCleaned = string.replace(jobLocationUnclean, c, "")
jobLocation = jobLocationCleaned

# Add to list
params.append(jobLocation)
print(jobLocation)

However, when using Debug I can see the code step through and do the job it is supposed to yet when it comes to the print statement it prints the address before it was cleaned, i.e. the for loop has no effect.

Why is this?

Upvotes: 1

Views: 241

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

You should use regex for this:

>>> import re
>>> from string import punctuation as punc
>>> strs = "Abc*@ddf%^sad#"
>>> re.sub(r'[{}]'.format(punc),'',strs)
'Abcddfsad'

Fixing your code:

>>> jobLocationUnclean = 'Abc*@ddf%sad#'
>>> for c in "!@#%&*()[]{}/?<>,.":
        #re-assign the new string to the `jobLocationUnclean`
        jobLocationUnclean = jobLocationUnclean.replace(c, "")
>>> jobLocationUnclean
'Abcddfsad'

Why your code failed?

In your code you are looping through those punctuations and assigning a replaced value of jobLocationUnclean to jobLocationCleaned, though note that strings are immutable in python so that replace(jobLocationUnclean, c, "") operation doesn't changes the original jobLocationUnclean at all. So,in each iteration you replaces a given punctuation and assign the new string to jobLocationCleaned. Any operation on a string always returns a new string.

>>> strs = "foo"
>>> strs.replace('f','i')
'ioo'
>>> strs  #original foo is still un-changed
'foo'

So in the end your code actually replaced only the . character in the string(jobLocationUnclean) and assigned that to jobLocationCleaned.

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208645

On each iteration you are doing the replacement on jobLocationUnclean but assigning the result to jobLocationClean. Since you use the same unclean starting point on each iteration only the last iteration will have any affect on the result. Try changing your code to the following:

jobLocation = jobLocationUnclean
for c in "!@#%&*()[]{}/?<>,.":
    jobLocation = jobLocation.replace(c, "")

params.append(jobLocation)
print(jobLocation)

Note that I also made two other minor modifications, I just use jobLocation and got rid of jobLocationClean because it is unnecessary, and instead of string.replace(jobLocation, c, "") I used jobLocation.replace(c, ""). This is the recommended way to call string functions, directly on the object rather than from the string module.

Upvotes: 4

Cthulhu
Cthulhu

Reputation: 1372

In the loop, you never use the result of previous iteration and use the original string instead. This is the root of your problems.

Upvotes: 9

Related Questions