繁体   English   中英

替换列表中的特殊字符python

[英]Replace special characters in a list python

我想用这个列表中的项目的下划线替换':'' ''-''('')'

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

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

  • 使用字典理解创建翻译表
  • 将翻译应用到列表元素

代码:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM