+ 5

Is there any way to replace items of a list with another item(Like maybe a replace function) in Python?

3rd Oct 2020, 7:50 PM
☃️🎄Abasiono Mbat☃️🎄
☃️🎄Abasiono Mbat☃️🎄 - avatar
8 Respuestas
+ 9
There are several approaches that can do this task. - you can use a for loop with an if condition inside - you can do the same with a list comprehension - if you have to replace a number of different items, it can also be done by using a dictionary. Please do a try by yourself first, then post your code here so that we may help you. thanks!
3rd Oct 2020, 8:04 PM
Lothar
Lothar - avatar
+ 6
Abasiono Mbat , i am not sure what to think about your "code". you are asking for a solution without being familiar with the basics of this programming language. this will not help you developing your skills. but since proposed solutions have already been made, mine is here: https://code.sololearn.com/cAc6L41At55b/?ref=app
4th Oct 2020, 11:45 AM
Lothar
Lothar - avatar
+ 4
I guess you could convert it to a string first: list = [] list.append("i") list.append("a") x = "".join(list) print(x.replace('a', 'b')) # Or, if you want a list output, list = [] list.append("i") list.append("a") x = "".join(list) print([_ for _ in x.replace('a', 'b')])
4th Oct 2020, 4:21 AM
David Ashton
David Ashton - avatar
+ 4
This works like the string replace method, but only on the first occurrence. lst = ["a", "b"] lst[lst.index("a")] = "z" print(lst) # output ['z', 'b'] To replace all occurrences of a character, I would use a comprehension with a ternary.
4th Oct 2020, 4:30 AM
David Ashton
David Ashton - avatar
+ 2
Here are a couple of functions that will do the trick: https://code.sololearn.com/c5szRqlZgbbh
4th Oct 2020, 10:12 AM
David Ashton
David Ashton - avatar
+ 1
# u may laugh😀😀😀 list = [] list.append("i") list.append("a") list.replace('a', 'b') x = "".join(list) print (x)
3rd Oct 2020, 8:35 PM
☃️🎄Abasiono Mbat☃️🎄
☃️🎄Abasiono Mbat☃️🎄 - avatar
0
That's my try
3rd Oct 2020, 8:36 PM
☃️🎄Abasiono Mbat☃️🎄
☃️🎄Abasiono Mbat☃️🎄 - avatar
- 2
Laugh as loud as you want LOL LOL LOL LOL LOL LOL
3rd Oct 2020, 8:36 PM
☃️🎄Abasiono Mbat☃️🎄
☃️🎄Abasiono Mbat☃️🎄 - avatar