Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the letters of a string with underscores? [duplicate]

Tags:

python

I'm trying to grab the letters in a string and replace them with an empty space, in this case the empty space is represented by "_" with a space between each underscore.

This is my code:

word = "my example"
def convert_letter(word):
    for i in range(0, len(word)):
        if ord(word[i]) != 32:
            word.replace(word[i], '_')
    print(word)
convert_letter(word)

When I run the code it just returns the word or string and I have no idea why.

Just in case you're wondering the purpose of the if statement is so that it doesn't convert the spaces to "_".

So in the case of this function I'm expecting the following:

_ _  _ _ _ _ _ _ _
like image 458
Sebastian Avatar asked Dec 03 '25 18:12

Sebastian


1 Answers

The problem in your code is that str.replace doesn't modify a string in place, but returns a copy with the replacement done. You have to assign it back if you want to replace the original string

word = word.replace(word[i], '_')

Make sure you understand the pieces you are working with, if you start with a simple program you can see that replace doesn't perform as you expect

w = 'abc'
w.replace('a', 'x') # should be w = w.replace(...)
print(w) # prints 'abc'

If I take the title of your question literally, you want to replace the letters with underscores only. That would leave all of the special characters and numbers intact. In that case you can use string.ascii_lettrs and join

def convert_letter(word):
    ''.join('_' if c in string.ascii_letters else c for c in word)

As you seem to have stated in other comments, you actually want the underscores to have a space between them, if that is the case then use ' '.join instead

like image 136
Ryan Haining Avatar answered Dec 06 '25 06:12

Ryan Haining