8

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.

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
Cheezey
  • 700
  • 2
  • 11
  • 29
  • I like the question "what is the pythonic way to strip 0s from the front of the string" but your saying that later it will be converted with `int()` seems to be a total red herring. Does it have anything at all to do with the question? Because `int` isn't going to care about the leading zeros. – Ray Toal Jun 02 '12 at 05:47
  • @RayToal: He means that he wants to strip leading zeros *and* the result must be a valid input for `int(s)`. The latter of course is automatic, as long as you do the first step correctly. – Mark Byers Jun 02 '12 at 07:39
  • if your concern is really just about the number beeing read as octal (like in your comments to ignacio's answer): `int` does not do that in python. `int('010')` would be `10`, `int('010', 0)` whould be `8`. If you want to be specific about it, just use `int('010', 10)`. – kratenko Jun 08 '12 at 10:58

3 Answers3

21

You can do it like this:

s = str(int(s))

Another alternative is:

s = s.lstrip('0') or '0'
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
5

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • That only strips one 0. I need to do this because Python interprets it as an Octal string. – Cheezey Jun 02 '12 at 05:33
  • @Cheezey: no, it strips multiple 0s. – DSM Jun 02 '12 at 05:34
  • Oh, it worked, but there was a different problem. Posting it in the main question now. – Cheezey Jun 02 '12 at 05:36
  • @IgnacioVazquez-Abrams: I think passing the radix is unnecessary. The octal problem comes in when parsing literals in source, not when int('0123') does its work, no? – DSM Jun 02 '12 at 05:37
  • @DSM `int('0123')` is 123 but `int('0123',8)` is 83. – Ray Toal Jun 02 '12 at 05:41
  • @RayToal: er, yes. Perhaps I'm misunderstanding -- I thought he was stripping zeroes unnecessarily to try to *avoid* a string being parsed as octal when it wasn't intended as such. Are you suggesting that instead his string *is* in base 8? If so, why would he need to strip it in the first place? – DSM Jun 02 '12 at 05:44
  • @DSM: His question is how to strip the leading zeros on a string like "012" -> "12" and "000" -> "0". It's a fairly normal and straight-forward question, don't you agree? Nothing to do with octal. – Mark Byers Jun 02 '12 at 05:47
  • @DSM good question, I have no idea. I've asked the OP in the main question. – Ray Toal Jun 02 '12 at 05:47
0

what about string[:-1].lstrip('0')? :D

yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42