简体   繁体   English

Python-MYSQL-选择前导零

[英]Python - MYSQL - Select leading zeros

When using Python and doing a Select statement to MYSQL to select 09 from a column the zero gets dropped and only the 9 gets printed. 当使用Python并对MYSQL执行Select语句以从一列中选择09时,将删除零,仅打印9。

Is there any way to pull all of the number ie including the leading zero? 有没有办法拉所有的数字,即包括前导零?

There's almost certainly something in either your query, your table definition, or an ORM you're using that thinks the column is numeric and is converting the results to integers. 几乎可以肯定,查询,表定义或正在使用的ORM中都包含某些内容,认为该列为数字并将结果转换为整数。 You'll have to define the column as a string (everywhere!) if you want to preserve leading zeroes. 如果要保留前导零,则必须将列定义为字符串(无处不在!)。

Edit: ZEROFILL on the server isn't going to cut it. 编辑:服务器上的ZEROFILL不会削减它。 Python treats integer columns as Python integers, and those don't have leading zeroes, period. Python将整数列视为Python整数,而这些整数没有前导零,句点。 You'll either have to change the column type to VARCHAR , use something like "%02d" % val in Python, or put a CAST(my_column AS VARCHAR) in the query. 您要么必须将列类型更改为VARCHAR ,要么在Python中使用"%02d" % val类的东西,或者在查询中放入CAST(my_column AS VARCHAR)

MySQL supports this in the column definition: MySQL在列定义中支持此功能:

CREATE TABLE MyTable (
  i TINYINT(2) ZEROFILL
);

INSERT INTO MyTable (i) VALUES (9);

SELECT * FROM MyTable;

+------+
| i    |
+------+
|   09 | 
+------+

Best option will be using CAST as suggested by Eevee but you have to use CAST ( ur_field AS CHAR(2) ) as casting to varchar has this problem as given in this post 最佳选择是按照Eevee建议使用CAST ,但是您必须使用CAST ( ur_field AS CHAR(2) )因为将其强制转换为varchar出现此问题

How to convert from varbinary to char/varchar in mysql 如何在MySQL中从varbinary转换为char / varchar

What data type is the column? 列是什么数据类型? If you want to preserve leading zeros, you should probably use a non-numeric column type such as VARCHAR . 如果要保留前导零,则可能应使用非数字列类型,例如VARCHAR

To format numbers with leading zeros in Python, use a format specifier: 要在Python中格式化带有前导零的数字,请使用格式说明符:

>>> print "%02d" % (1,)
01

You could run each query on that column through a function such as: 您可以通过以下函数在该列上运行每个查询:

if len(str(number)) == 1: number = "0" + str(number)

This would cast the number to a string but as far as I know, Python doesn't allow leading zeroes in its number datatypes. 这会将数字转换为字符串,但是据我所知,Python不允许在其数字数据类型中使用前导零。 Someone correct me if I'm wrong. 如果我错了,请有人纠正我。

Edit: John Millikin's answer does the same thing as this but is more efficient. 编辑:约翰·米利金(John Millikin)的答案与此相同,但效率更高。 Thanks for teaching me about format specifiers! 感谢您教我有关格式说明符的知识!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM