我正在寻找创建一个函数,该函数会将具有地址值的字典转换为具有特定顺序的字符串值。我还需要考虑缺失值(某些地址不会有第二或第三条地址行。我希望输出如下所示,以便可以将用新行分隔的文本块复制到数据库字段中。

name
contact
addr1
addr2 (if not empty)
addr3 (if not empty)
city, state zip
phone


我有以下创建字典的内容,但是我仍然坚持创建忽略空值并将所有内容按正确顺序放置的字符串对象。

def setShippingAddr(name, contact, addr1, addr2, addr3, city, state, zipCode, phone):
    addDict = {'name': name, 'contact': contact, 'addr1': addr1,
               'city': city, 'state': state, 'zip': zipCode, 'phone': phone}
    if addr2 is True:    # append dict if addr2/addr 3 are True
        addDict['addr2'] = addr2
    if addr3 is True:
        addDict['addr3'] = addr3

    shAddr =     # This is where i need to create the string object
    return shAddr

最佳答案

我将重写该函数以仅返回字符串,而字典则不是必需的:

def setShippingAddr(name, contact, addr1, city, state, zipCode, phone, addr2=None, addr3=None):
    shAddr = f'{name}\n{contact}\n{addr1}'
    shAddr = f'{shAddr}\n{addr2}' if addr2 else shAddr
    shAddr = f'{shAddr}\n{addr3}' if addr3 else shAddr
    shAddr = f'{shAddr}\n{city}, {state} {zipCode}\n{phone}'
    return shAddr

10-06 12:35