tags:

views:

84

answers:

3

Hi,

Using Python 2.6


I want to be able to convert numbers such as 00000, 000.00004 and 001 to strings. Such that each string is '00000', '000.00004' and '001' respectively.

It is also necessary that the way to do this is the same with all numbers, and also copes when letters are fed into it. E.g. foo should become 'foo', 2bar should be become '2bar' but 001 should still be '001'.


Using str([object]) the above numbers would go to '0', '4e-05' and '1' respectively.



Any ideas?

EDIT:

@unholysampler (and everyone else) you are of course right.

I was simply getting confused because Sqlite3 was taking strings and then converting them to integers or floating point numbers when putting them into it's database, despite it being declared as a string column. But this is another issue entirely.

SECOND EDIT:

If anybody was curious why Sqlite3 was doing that, it was because I had actually set the column to be of type 'STRING' in the schema, where it should have been type 'TEXT' (see http://www.sqlite.org/datatype3.html) - this was combined with Sqlite's "dynamic typing" (see http://www.sqlite.org/faq.html#q3) and was enough to make me confused :-)

Thank you for giving nice answers anyway :D

+8  A: 

There is no number 0000 or 001. There is only 0 and 1. If you want to produce a string representation of a number, you can use string formatting to pad zeros.

n = 1
print '%03d' % n //001
unholysampler
A: 

Well, the problem you're facing here is that 00000 is not 00000, but rather the constant 0. The same is true for 001 and 1. If you'd like to represent numbers in a more "true" way, you can try using the repr(obj) method, or use string formatting.

 print '%05d, %03.7f, %03d' % (0,0.0000004,1)
sleepynate
A: 

The first step would be: however you are getting a number that you think should be 00000 instead of 0 ... don't actually convert it to a number. Just keep it as a string.

detly