填充函数(Python)字符串.zfi

2024-09-30 20:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改下面的Python函数,以涵盖我的business_代码需要填充的所有情况。string.zfillPython函数处理此异常,将填充到左侧直到达到给定的宽度,但我以前从未使用过它。在

 #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. 在


Tags: lambda函数代码stringlenifcodebusiness
2条回答
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)  

您可以使用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)

^{pr2}$

格式{:06d}可以理解为:

  • {...}表示用format中的参数替换以下内容, (例如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)

相关问题 更多 >