views:

164

answers:

4

Say I got a random word like WORD, i want to replace each of the letters of the word with _. How can I do it? Also, say if there is a space between the word like WO RD, I don't want it to replace the space with _.

+3  A: 
word = 'WORD'
word = ''.join(['_' if char != ' ' else char for char in word])
Blue Peppers
you don't need list comprehension there
SilentGhost
+2  A: 
polygenelubricants
35k of reputation and I need to comment about using variable names shadowing built-in.
SilentGhost
say the i want to do the same thing but now i dont want to replace any letter in the word WO RD. ex the letter O. _ O _ _ how is that possible?
babikar
say under= re.sub(r"[A-Za-z]", "_ ", word) i think i have to add something in that code to say like except O. how?
babikar
@babikar: I've given a set-based approach; I think this is better if the filtering pattern is evolving.
polygenelubricants
i dono why but i keep on getting an error for the "," in the first line of the code!
babikar
@babikar: look at the `set` documentation if you're using older version of Python; you may have to use the deprecated http://docs.python.org/library/sets.html
polygenelubricants
i mean the first part works:word= 'WO RD' under= re.sub(r"[A-Za-z]", "_ ", word)but the second part gives error: visible = {' ', 'O'} word_O = ''.join(char if char in visible else '_' for char in word)print(word)and i dont think there is anything that has to do with the version, cuz we are not using anything new. i guess
babikar
im using python 2.6.2
babikar
@babikar: If I understand it correctly, that means you have to use the deprecated sets module. This snippet http://ideone.com/8E1tT works for 2.6.4.
polygenelubricants
i think i got it. thanx alot
babikar
A: 
"".join(['_' if x != ' ' else x for x in word])
Ed
you don't need list comprehension there
SilentGhost
+2  A: 

You could do this with Python's translate() and maketrans() functions. They will take care of mapping letters in one string to other letters.

Karmastan