When I was doing questions on Chapter 14 on Computer Science Circles, I found something weird.
The question said: "Define a function postalValidate(S) which first checks if S represents a postal code which is valid: first, delete all spaces; the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers. If S is not a valid postal code, return the boolean False. If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital."
and this is my working for this question:
def postalValidate(S):
if S.count(' ') > 0:
S.replace(' ', '')
if S.isalpha() or S.isdigit() == True:
return False
else:
if S[0].isalpha() and S[2].isalpha() and S[4].isalpha() == False:
return False
else:
if S[1].isdigit() and S[3].isdigit() and S[5].isdigit() == False:
return False
else:
return S.upper()
All the inputs were correct except this postalValidate(' d3 L3 T3'). I used S.count to identify how many ' ' are there in the input, but it didn't work. Instead, the input turned out to be 'd3L3T3' right after it goes into the function.
Is there proper way to count ' ' string? Or is there other ways to remove ' ' in the string instead of using string methods?
S,S = S.replace(' ', ''); strings are immutable andstr.replaceis not in-placeif S[0].isalpha() and S[2].isalpha() and S[4].isalpha() == False:intended to check whether all of those conditions are False? At the moment it's equivalent toif S[0].isalpha() == True and S[2].isalpha() == True and S[4].isalpha() == False:which I don't think you intendedif not S[0].isalpha() and not S[2].isalpha() and not S[4].isalpha():. For longer lists of conditions you might want to useany()orall(). But at the moment, it's not doing what you think it's doing. I'm not even sure you should be usingandbutorinstead.