Reputation: 187
I have already seen this issue but it seems not fit for my specific use case.
I have a file called whitelist where I save a number that indicates a type of device and the ID of such devices. The format is something like 37423 = -212, -210, 276
where, in this case, 37423
is the number of the device type and -212, -210, 276
are the IDs.
Now, I have a code that scans this type of file and adds into a list the IDs:
if not(manufacturedid in whitelist):
whitelist[manufacturedid] = list()
for d in deviceid:
tmp_d = re.sub(r'\W+', '', d)
if not (tmp_d in whitelist[manufacturedid]):
whitelist[manufacturedid].append(tmp_d)
where manufacturedid
is 37423
and tmp_d
are -212, -210, 276
My issue is that when it .append(tmp_d)
is a negative number, it converts into a positive one and I can't understand why as the tmp_d
in the if not
statement should be negative as well.
EDIT: I think the issue is in the for d
loop as d
results always positive
Upvotes: 0
Views: 196
Reputation: 36680
You did
tmp_d = re.sub(r'\W+', '', d)
as you are dealing with ASCII text we can say \W
is simply [^a-zA-Z0-9_]
, thus it was also match and remove -
, for example
import re
print(re.sub(r'\W+', '', '-212'))
output
212
Read python re
built-in module docs, if you want to know more about \W
.
Upvotes: 4
Reputation: 28974
It is not append but re.sub(r'\W+', '', d)
that makes tmp_d
positive.
Debugging helps with such issues. If the output is not what you expect. Check the input first.
Upvotes: 2