Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替换python列表中的特殊字符_Python_List_Replace - Fatal编程技术网

替换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]