-3

I would like to replace ':',' ', '-', '(', and ')' with an underscore for the items in this list:

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

So that:

columns = ['Region', 'Cat', 'Bld', 'Fbld', 'Ht_m', 'H_W', 'Fperv', 'Froof', 'wall_type', 'roof_type', 'road_type', 'Tmn', 'Tmx', 'Notes']

The goal is to replace all special characters and space so that it can be read into an sql table. Thanks for any help.

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
Wendy C
  • 31
  • 1
  • 3

1 Answers1

3

Since you provided a list of the special characters, you could:

  • create a translation table using dict comprehension
  • apply the translation to the elements of your list

code:

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)

result:

['Region', 'Cat', 'Bld', 'Fbld', 'Ht_m_', 'H_W', 'Fperv', 'Froof', 'wall type', 'roof type', 'road_type', 'Tmn', 'Tmx', 'Notes']

The classic regex solution as an alternative:

import re
new_list = [re.sub("[:\-() ]","_",x) for x in orig_list]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219