String to int newbie question

Gerrit Holl gerrit at nl.linux.org
Sat Mar 22 11:43:52 EST 2003


Boris Genz schreef op zaterdag 22 maart om 14:46:53 +0000:
> I have the following problem:
> I want to convert a number string ( '3211' for example ) to a number, 
> ( actually integer ) preserving the original number ( the exact number being
> string and integer ), but if my number string starts with one or more zeroes,
> then the numbers won't be same...
> For example, if I have string = '0027' then int(string) would give 27.
> How can I add leading zeroes to that number?
> I know it's a rather stupid question, but please help...

First, count the number of zeros on the start:

  3 >>> len(s) - len(s.lstrip('0'))
2

Then, convert s to i:

  4 >>> i = int(s)
  5 >>> i

Now, convert i back to s:

  6 >>> s2 = str(i)
  7 >>> s2

Finally, use the zfill method:
  8 >>> s2.zfill(len(s2) + len(s) - len(s.lstrip('0')))
'0027'

Hope this helps!

yours,
Gerrit.

-- 
258. If any one hire an ox-driver, he shall pay him six gur of corn per
year. 
        -- Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list