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
  • 1
    Welcome to Stack Overflow! Please take the [tour], read [what's on-topic here](/help/on-topic) and [ask], and provide a [mre]. "Implement this feature for me" is off-topic for this site. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. [Asking on Stack Overflow is not a substitute for doing your own research.](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Oct 16 '20 at 15:34
  • @PranavHosangadi Alright! Thank you! Should I edit my post or leave it as is for now? – sanguinis Oct 16 '20 at 15:37

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
  • 1,774
  • 1
  • 3
  • 21
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,263
  • 2
  • 10
  • 29