2017-02-07 42 views
-4

我想与此列表中的项目下划线来代替':'' ''-''(',并')'列表中的蟒蛇替换特殊字符

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表中。谢谢你的帮助。

+0

的可能的复制[?如何把参数化的SQL查询到的变量,然后在Python执行(http://stackoverflow.com/questions/ 1633332 /如何到把参数化-SQL查询 - 到 - 可变和当时的执行功能于蟒蛇) – cpburnz

回答

1

由于您提供的特殊字符的列表,你可以:

  • 使用字典理解
  • 翻译应用到你的列表

代码的元素创建一个翻译表:

orig_list = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht(m)', 'H:W', 'Fperv', 'Froof', 'wall type', 'roof type', 'road-type', 'Tmn', 'Tmx', 'Notes'] 

d = {ord(x):"_" for x in ":-() "} 
new_list = [x.translate(d) for x in orig_list] 

print(new_list) 

结果:

['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]