将浮点型转换为字符串而不会截断前导零或尾随零 [英] Converting Float to String without Truncating leading or trailing zeros

查看:126
本文介绍了将浮点型转换为字符串而不会截断前导零或尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel电子表格中提取邮政编码,并将其作为字符串加载到列表中.

I'm trying to extract Zip Codes from an Excel Spreadsheet and load them into a list as Strings.

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电子表格也被某些商业智能系统使用.因此,将该字段从数字更改为字符串可能会对利用此工作簿的其他工作流造成问题,而我对此并不了解.

Unfortunately, this Excel workbook is managed by someone else so I cannot simply go and convert the field holding zip codes in the excel spreadsheet to text to solve my problem. In addition, believe it or not, this Excel spreadsheet also is used by some business intelligence systems. So changing that field from number to String could cause problems for other workflows leveraging this workbook, which I am not privy to.

我发现的是,当我直接打印数字而不先转换为整数或字符串时,我当然会得到一堆浮点数.我期望如此,因为Excel将数字存储为浮点数.

What I'm finding is that when I print the numbers as they are without casting to integer or string first, I of course get a bunch of floats. I expected that, since Excel stores numbers as floats.

>>>Zips
[u'06405',
 04650.0,
 10017.0,
 71055.0,
 70801.0]

我没想到的是,当我将这些浮点数转换为整数以摆脱十进制值,然后将其转换为字符串时,结果是邮政编码中的任何前导零或尾随零值被截断.

What I didn't expect is that when I cast these floats as int to get rid of the decimal values, then cast the result of that as string the result is that any leading or trailing zero which are part of the zip code value are truncated.

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']

如何在不删除前导或尾随零的情况下将这些邮政编码转换为字符串,或者如何在截断之前确定值的前导和尾随零的数目并将其适当地附加回去?

How can I convert these zip codes to string without dropping the leading or trailing zeros or determine the number of leading and trailing zeros on the value prior to truncation and append them back as appropriate?

推荐答案

所有邮政编码(不包括Zip + 4)均为5个字符,因此您只需填充5个即可:

All ZIP codes (not including the Zip+4) are 5 characters so you could just pad out to 5:

C#

  • Use the String.Pad left method: https://msdn.microsoft.com/en-us/library/system.string.padleft%28v=vs.110%29.aspx
  • ZIPs.append(str.PadLeft(5, '0');

Python:

  • Use rjust: http://www.tutorialspoint.com/python/string_rjust.htm
  • ZIPs.append(str(int(record.value)).rjust(5, '0'))

这篇关于将浮点型转换为字符串而不会截断前导零或尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆