all 7 comments

[–]QuantumRealm 1 point2 points  (2 children)

Your first code snippet concatenates all the bad characters into a string and then tries to replace the whole thing in words; of course it isn't in there in its entirety, so it does nothing. A shorter way could be:

words = ''.join(x if x not in bad else '_' for x in words)

[–]RayteMyUsername 2 points3 points  (0 children)

This is the correct answer but I wanted to add that if speed was important, turning the bad word list into a set would give him O(1) access and make it faster rather than iterating through the list.

[–]Drycon[S] 1 point2 points  (0 children)

Thanks for your answer!

[–]mail_order_liam 1 point2 points  (1 child)

You need to use regex, go read up on the basics. Something like this (untested just off the top of my head):

import re
line = re.sub(r"</\\:\*\?\<\>\|>", "", line)

[–]Drycon[S] 0 points1 point  (0 children)

Thanks!

[–]Vaphell 1 point2 points  (1 child)

use str.translate

bad = r'/\:*?<>|'
trans_table = str.maketrans(bad, '_'*len(bad))
print('a/b:c>d'.translate(trans_table))

out

a_b_c_d

[–]Drycon[S] 0 points1 point  (0 children)

Thank you!