0
list
how we can change the letters of the words? l know we can change the index of the list. but if we have one index in the list and want to change , is that possible??
2 Respostas
+ 7
If you have a string and want to change a letter (all occurrencies of this letter) you can use replace()
txt = "abcXee"
txt = txt.replace("e", "E")
result is: "abcXEE"
If you have a string and want to change one of the letters somewhere in this string, you can NOT use index numbers to do this, because strings are immutable. they can not be changed.
txt = "abcXee" # "X" has index 3
txt[3] = "*"
>>> you get this error: TypeError: 'str' object does not support item assignment
except the letter to change is the first letter or last letter of the string (this can be done by using slices), it is better to convert the string to a list of individual characters.
lst = list(txt)
# lst will be: ['a', 'b', 'c', 'X', 'e', 'e']
with this list you can iterate over or you can use index numbers to replace characters. after this is done, the list can be converted back to a string by using
new_str = ''.join(lst)
+ 3
#basically.
name = "Cindy"
namechange = 'M' + name[1:]
#also this:
name = ['C','i','n','d','y']
name.pop(0)
name.insert(0,'M')
for lett in name:
print(lett, end='')