Python, convert a number to a string 'as is'
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
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
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.
精彩评论