我想更改下面的Python函数,以涵盖我的business_代码需要填充的所有情况。string.zfill
Python函数处理此异常,将填充到左侧直到达到给定的宽度,但我以前从未使用过它。在
#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的业务代码,但我发现业务代码的长度不同。我正在逐个状态验证数据。每个州的商业代码长度各不相同(IL-6长度,OH-8长度)。所有代码必须均匀填充。所以IL的代码是10应该产生000010,等等,我需要处理所有的异常。使用命令行解析参数(argparse),以及字符串.zfill. 在
您可以使用str.format:
^{pr2}$
格式
{:06d}
可以理解为:{...}
表示用format
中的参数替换以下内容, (例如code
)。在:
开始格式规范0
启用零填充6
是字符串的宽度。注意大于6的数字 但是,数字不会被截断。在d
表示参数(例如code
)应为整数类型。在注意,在Python2.6中,格式字符串需要额外的0:
相关问题 更多 >
编程相关推荐