替换python列表中的特殊字符
我想将“:”、“-”和替换为此列表中项目的下划线:替换python列表中的特殊字符,python,list,replace,Python,List,Replace,我想将“:”、“-”和替换为此列表中项目的下划线: columns = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht(m)', 'H:W', 'Fperv', 'Froof', 'wall type', 'roof type', 'road-type', 'Tmn', 'Tmx', 'Notes'] 以便: columns = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht_m', 'H_W', 'Fperv', 'Froof', 'wal
columns = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht(m)', 'H:W', 'Fperv', 'Froof', 'wall type', 'roof type', 'road-type', 'Tmn', 'Tmx', 'Notes']
以便:
columns = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht_m', 'H_W', 'Fperv', 'Froof', 'wall_type', 'roof_type', 'road_type', 'Tmn', 'Tmx', 'Notes']
目标是替换所有特殊字符和空格,以便可以将其读入sql表。感谢您的帮助。由于您提供了特殊字符列表,您可以: 使用dict comprehension创建翻译表 将翻译应用于列表中的元素 代码: 结果:
['Region', 'Cat', 'Bld', 'Fbld', 'Ht_m_', 'H_W', 'Fperv', 'Froof', 'wall type', 'roof type', 'road_type', 'Tmn', 'Tmx', 'Notes']
作为替代方案的经典正则表达式解决方案:
import re
new_list = [re.sub("[:\-() ]","_",x) for x in orig_list]
可能重复的
import re
new_list = [re.sub("[:\-() ]","_",x) for x in orig_list]