将浮点数转换为字符串而不截断前导或尾随零
问题描述:
我试图从Excel电子表格中提取邮政编码并将它们作为字符串加载到列表中。将浮点数转换为字符串而不截断前导或尾随零
import xlrd
BIL = xlrd.open_workbook(r"C:\Temp\Stores.xls)
Worksheet = BIL.sheet_by_name("Open_Locations")
ZIPs = []
for record in Worksheet.col(17):
if record.value == "Zip":
pass
else:
ZIPs.append(record.value)
不幸的是,这个Excel工作簿是别人,所以我不能简单地去转换领域保持邮政编码Excel电子表格文本来解决我的问题管理。另外,不管你信不信,这个Excel电子表格也被一些商业智能系统所使用。因此,将该字段从数字更改为字符串可能会对利用此工作簿的其他工作流程造成问题,这是我不知道的。
我在找的是当我打印数字,因为他们是没有铸造成整数或字符串第一,我当然会得到一堆浮游物。我预计,因为Excel将数字存储为浮点数。
>>>Zips
[u'06405',
04650.0,
10017.0,
71055.0,
70801.0]
我没想到的是什么,当我投这些花车为INT摆脱十进制值,然后投中那个结果作为字符串的结果是,任何开头或结尾零,这是部分的邮政编码值被截断。
import xlrd
BIL = xlrd.open_workbook(r"C:\Temp\Stores.xls)
Worksheet = BIL.sheet_by_name("Open_Locations")
ZIPs = []
for record in Worksheet.col(17):
if record.value == "Zip":
pass
else:
ZIPs.append(str(int(record.value)))
>>>Zips
['6405',
'465',
'10017',
'71055',
'70801']
我怎样才能将这些邮政编码串不失领先或尾随零或确定的领导和上截断和追加他们回到适当的事先值尾随零的数量?
答
所有邮政编码(不包括邮编+ 4)5个字符,所以你可以只垫了5:
C#
- 使用String.Pad左方法: https://msdn.microsoft.com/en-us/library/system.string.padleft%28v=vs.110%29.aspx
ZIPs.append(str.PadLeft(5, '0');
的Python:
- 使用rjust:http://www.tutorialspoint.com/python/string_rjust.htm
ZIPs.append(str(int(record.value)).rjust(5, '0'))
答
因此,一些修修补补后,原来的答案是:
- 不投邮政编码为int,因为这也将截断任何 前导零
- 将字符串显式编码为utf-8
Unicode字符串指标的存在放倒我了,这可能是答案,当它出现在一些值,但不是所有的时候我打印列表
for record in Worksheet.col(17):
if record.value == "Zip":
pass
else:
# In this case, the value is still being returned as float, because
it has 1 significant digit of 0 appended to the end. So we'll cast
as string and explicitly encode it as utf-8 which will retain the
leading and trailing zeros of the value and also truncate the
significant digits via index.
if len(str(record.value).encode('utf-8')) > 5
ZIPs.append(str(record.value).encode('utf-8'))
else:
# In this case, the value is already being returned as a unicode
string for some reason, probably because of poor excel worksheet
management, but in any case cast as string and explicitly encode
as utf-8 just for peace of mind.
ZIPs.append(str(record.value).encode('utf-8'))
>>>Zips
['06405',
'04650',
'10017',
'71055',
'70801']
如果任何人有这样做的更优雅的方式, 我很乐意看看。
答
你可以尝试通过字符串操作来做到这一点。
我们在这里的假设是该列将是邮政编码,所以'.0'最后永远不会有必要。
下面会去你的else语句:
record_str = str(record.value)
formatted_record = record_str[:-2] if record_str.endswith('.0') else record_str
ZIPs.append(formatted_record)
或者,如果你想成为我们的淫秽这里假定将阅读本专栏将始终有一个” 0.0' ,否则它可能会导致意外的行为。
ZIPs.append(str(record.value)[:-2])
谢谢Al。 rjust()会将任意零附加到zip的开头,将06405的一个zip截断为6405,然后将其截断为06405.但是,如果前导和尾随的零都被截断,例如04650这样的邮政编码截断为465 ,使用rjust()会返回一个00465的值,这是与原始zip完全不同的结果。关键似乎是确定在zip中有多少前导或尾随零,然后根据需要在两端填充零。我已经修正了问题的zip示例以反映这一点 – MrBubbles 2015-02-09 18:06:32