Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to strip all 0's from the front of a string

Tags:

python

I have a string that will later be converted with int(). It is three digits, anywhere from 0 to 3 of them might be 0's. How would I strip the 0s from the left side of the string?

Now I'm using string.lstrip('0') but that strips all the 0s and makes the string empty, causing an error.

like image 981
Cheezey Avatar asked Jun 02 '12 05:06

Cheezey


2 Answers

You can do it like this:

s = str(int(s))

Another alternative is:

s = s.lstrip('0') or '0'
like image 99
Mark Byers Avatar answered Oct 27 '22 01:10

Mark Byers


You want str.lstrip() for that. But maybe you should just pass the radix to int().

like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 26 '22 23:10

Ignacio Vazquez-Abrams