0

How could I remove all the illegal characters from each string in the my_titles list and replace them with an underscore?

Here is my code:

illegal_chars=['?',':','>','<','|']
my_titles=['Memoirs | 2018','>Example<','May: the 15th']

Would I have to use a nested for loop or is there an easier/cleaner way to do it? Thank you!

sanguinis
  • 21
  • 3

3 Answers3

1
illegal_chars=['?',':','>','<','|']
my_titles=['Memoirs | 2018','>Example<','May: the 15th']
new_titles = []
for i in my_titles:
    for j in illegal_chars:
        if j in i:
            i = i.replace(j,'_')
            new_titles.append(i)

print(new_titles)
Divyessh
  • 2,540
  • 1
  • 7
  • 24
1

How about something like this?

illegal_chars=['?',':','>','<','|']
my_titles=['Memoirs | 2018','>Example<','May: the 15th']

for i in range(len(my_titles)):
   for char in illegal_chars:
      if char in my_titles[i]:
         my_titles[i] = my_titles[i].replace(char, "_")
1

Try this:

for i in illegal_chars:
    my_titles=[k.replace(i, '_') for k in my_titles]

>>> print(my_titles)
['Memoirs _ 2018', '_Example_', 'May_ the 15th']
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30