替换列表中出现的字符串部分

时间:2014-03-18 22:25:52

标签: python string

好吧,我正在制作一个需要从用户那里获取客户信息的程序,需要填写各种字段。如果字母数字值的值留空,我需要通过默认将该值设置为空白,因此单个whitesapce字符。如果数值保持空白,我需要使其等于0

    def insertion(new_record):
    field_names = ['Customer_ID=',
    'Last_Name=',
    'First_Name=',
    'Street_Address=',
    'City=',
    'Province=',
    'Postal_Code=',
    ]
    field_names2 = ['Home_Phone=',
    'Business_Phone=']

    if new_record[3:5] == 'CU':
        for i in field_names:
            if i in new_record:
                new_record.replace()

这里的想法是,如果用户留空,我列出了字段名称的样子。因此,如果field_namesnumeric_field_names中的任何项目出现在字符串中,则表示用户将该字段留空。我想相应地替换输入中的那些字符串,然后将它们写入文件。在这种情况下,我可以迭代new_record来替换这些字符串吗?另请注意,输入始终为多行。

修改

这就是我调用函数的方式:

insertion('''IN CU
Customer_ID=474
Last_Name=Sanderson
First_Name=John
Street_Address=17 Chestwood Ave
City=Scarborough
Province=Ont
Postal_Code=M9C2C7
Home_Phone=416/227-3297
Business_Phone=416/997-2923
//'''
)

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用字典,而不是使用列表。

def insertion(new_record):
    newRecordDict={r.split('=')[0]:r.split('=')[1] for r in new_record.split('\n')[1:-1]} #first and last line is ignored
    field_names = {'Customer_ID':None,
    'Last_Name':None,
    'First_Name':None,
    'Street_Address':None,
    'City':None,
    'Province':None,
    'Postal_Code':None,
    }
    field_names2 = {'Home_Phone':0,'Business_Phone':0}

    for field in field_names:
        field_names[field] = newRecordDict.get(field,None)
    for field in field_names2:
        field_names2[field] = newRecordDict.get(field,None)

    print field_names
    print field_names2

实际上,您可以将所有数据保存到一个字典而不是field_names和field_names2。您可以接听相同的电话。在上面的代码中,基于更新的字段,field_names和field_names2,来自在newRecordDict中作为字典加载的用户的所有数据都被更新。以下是输出:

{'Province': 'Ont', 'City': 'Scarborough', 'First_Name': 'John', 'Last_Name': 'Sanderson', 'Postal_Code': 'M9C2C7', 'Customer_ID': '474', 'Street_Address': '17 Chestwood Ave'} 

{'Business_Phone': '416/997-2923', 'Home_Phone': '416/227-3297'}

现在,如果您想访问省份'从field_names,您可以使用:

field_names['Province']

返回' Ont'。同样,它适用于所有其他领域。

相关问题