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:
_ _ _ _ _ _ _ _ _
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With