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 _.
views:
164answers:
4
                +3 
                A: 
                
                
              word = 'WORD'
word = ''.join(['_' if char != ' ' else char for char in word])
                  Blue Peppers
                   2010-07-20 16:57:06
                
              you don't need list comprehension there
                  SilentGhost
                   2010-07-20 17:00:41
                35k of reputation and I need to comment about using variable names shadowing built-in.
                  SilentGhost
                   2010-07-20 17:18:40
                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
                   2010-07-20 17:50:12
                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
                   2010-07-20 18:04:27
                @babikar: I've given a set-based approach; I think this is better if the filtering pattern is evolving.
                  polygenelubricants
                   2010-07-20 18:11:42
                i dono why but i keep on getting an error for the "," in the first line of the code!
                  babikar
                   2010-07-20 18:25:00
                @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
                   2010-07-20 18:33:41
                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
                   2010-07-20 18:40:18
                @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
                   2010-07-20 18:46:27
                
                +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
                   2010-07-20 16:59:02