Sunday, August 8, 2010

Python - remove leading zeros

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)

7 comments:

  1. Incorrect. Use the following:

    newstring = re.sub("^0","",oldstring)

    ReplyDelete
  2. It is correct. But using your way you remove only one leading zero. See edit for an improvement

    ReplyDelete
  3. Couldn't you just do:

    newstring = oldstring.lstrip('0')

    ReplyDelete
  4. Anonymous is correct. Avoid RE, they are expensive.

    ReplyDelete
  5. What do you mean by "expensive"? Slow?

    ReplyDelete
  6. a newbie to python, but if you are just working with strings that are basically integers, couldn't you strip leading zeros using:

    str(int('0040'))

    ReplyDelete
    Replies
    1. 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