The problem is that you are not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
Answer from Matti Virkkunen on Stack OverflowThe problem is that you are not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.
line[8] = line[8].replace(letter, "")
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
def remove_chars(line):
line7=line[7].translate(None,'abcd')
return line[:7]+[line7]+line[8:]
line= ['ad','da','sdf','asd',
'3424','342sfas','asdfaf','sdfa',
'afase']
print line[7]
line = remove_chars(line)
print line[7]
Making str.replace() accept lists - Ideas - Discussions on Python.org
Python: How can I replace one specific character on a string while leaving the rest of the string as it was?
How to replace a string that is all the same character at a specific index?
Is there an easier way to replace multiple different things at once
word1 = input("Word: ") # lets say that the given word is "tower"
word2 = "********************"
word2 = word2.replace(word[3], word[3])
print(word2)
# Now the my code replaces all the "*" characters with the character "e"
# It just prints "eeeeeeeeeeeeeeeeeeee"
# I would like the code only to replace the 4th character with the other strings 4th
# I'd like it to print "***e****************"
For example, you have a string that is
string1='aaaaaa'
How would I replace just the last character with 'b'?
I tried
string1=string1.replace(string1[-1],b)
But that results in 'bbbbbb' as the output. It looks like the reason is due to string1[-1] being 'a'. So it replaces every 'a' with 'b' instead of just the last one.