【问题标题】:Replace special characters in a list python替换列表python中的特殊字符
【发布时间】:2017-06-24 23:53:13
【问题描述】:

我想将此列表中的项目的':'' ''-''('')' 替换为下划线:

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

【问题讨论】:

    标签: python list replace


    【解决方案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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-22
      • 2022-01-22
      • 2017-01-21
      • 2014-07-13
      • 1970-01-01
      • 2017-05-26
      • 2014-11-03
      • 2017-07-05
      相关资源
      最近更新 更多