To remove one or more leading zeros from the string eg. convert 0040 into 40:
import re
oldstring = '0040'
newstring = re.sub(r"\b0{2}","",oldstring)
To remove different number of zeros change the number in {} in the code.
EDIT:
Better way:
import re
oldstring = '0040'
newstring = re.sub("^0+","",oldstring)
Incorrect. Use the following:
ReplyDeletenewstring = re.sub("^0","",oldstring)
It is correct. But using your way you remove only one leading zero. See edit for an improvement
ReplyDeleteCouldn't you just do:
ReplyDeletenewstring = oldstring.lstrip('0')
Anonymous is correct. Avoid RE, they are expensive.
ReplyDeleteWhat do you mean by "expensive"? Slow?
ReplyDeletea newbie to python, but if you are just working with strings that are basically integers, couldn't you strip leading zeros using:
ReplyDeletestr(int('0040'))
Have you tried str(int('0080')) and str(int('0090'))? I just found out they do not work. Python interprets an int with a leading zero as octal.
Delete