[英]Replace parts of string that occur within a list
好的,我正在编写一个程序,该程序需要从用户那里获取有关客户的信息,需要填写各个字段。而且,如果字母数字值的值留为空白,则我默认需要将该值设置为空白,因此是一个空白字符。 如果数值留空,我需要使其等于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_names
或numeric_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
//'''
)
除了使用列表,您还可以通过以下方式使用字典。
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。您可以致电查询。 在上面的代码中,所有来自作为字典的用户的数据都将在newRecordDict中基于更新的字段field_names和field_names2进行更新。 以下是输出:
{'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”。 同样,它适用于所有其他领域。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.