填充函数(Python)string.zfill
我想更改下面的Python函数,以涵盖我的business_code需要填充的所有情况。 Python函数处理这个异常,填充到左边,直到达到给定的宽度,但我从来没有使用过它。填充函数(Python)string.zfill
#function for formating business codes def formatBusinessCodes(code):
""" Function that formats business codes. Pass in a business code which will convert to a string with 6 digits """
busCode=str(code)
if len(busCode)==1:
busCode='00000'+busCode
elif len(busCode)==2:
busCode='0000'+busCode
else:
if len(busCode)==3:
busCode='000'+busCode
return busCode
#pad extra zeros
df2['business_code']=df2['business_code'].apply(lambda x: formatBusinessCodes(x))
businessframe['business_code']=businessframe['business_code'].apply(lambda x: formatBusinessCodes(x))
financialframe['business_code']=financialframe['business_code'].apply(lambda x: formatBusinessCodes(x))
上面的代码处理长度为6的business_code但我发现的business_codes在长度<变化和> 6。我被状态验证数据状态。每个州的商业代码长度都不相同(IL - 6 len,OH - 8 len)。所有代码必须均匀填充。所以IL为10的代码应该产生000010等,我需要处理所有异常。使用命令行解析参数(argparse)和string.zfill。
回答:
你可以使用str.format:
def formatBusinessCodes(code): """ Function that formats business codes. Pass in a business code which will convert to a string with 6 digits """
return '{:06d}'.format(code)
In [23]: formatBusinessCodes(1) Out[25]: '000001'
In [26]: formatBusinessCodes(10)
Out[26]: '000010'
In [27]: formatBusinessCodes(123)
Out[27]: '000123'
格式{:06d}
可作如下理解:
{...}
手段代替从参数如下, (例如,code
)。:
开始格式规范0
使零填充6
是字符串的宽度。请注意,大于6 数字的数字不会被截断,但是。d
表示参数(例如code
)应该是整型。在python2.6的
注意格式字符串需要一个额外的0:
def formatBusinessCodes(code): """ Function that formats business codes. Pass in a business code which will convert to a string with 6 digits """
return '{0:06d}'.format(code)
回答:
parser.add_argument('-b',help='Specify length of the district code') businessformat=args.d
businessformat=businessformat.strip()
df2['business_code']=df2['business_code'].apply(lambda x: str(x))
def formatBusinessCodes(code):
bus=code bus.zfill(4)
return bus
formatBusinessCodes(businessformat)
以上是 填充函数(Python)string.zfill 的全部内容, 来源链接: utcz.com/qa/265663.html