+ 5
Is there any way to replace items of a list with another item(Like maybe a replace function) in Python?
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!
+ 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
+ 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')])
+ 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.
+ 2
Here are a couple of functions that will do the trick:
https://code.sololearn.com/c5szRqlZgbbh
+ 1
# u may laugh😀😀😀
list = []
list.append("i")
list.append("a")
list.replace('a', 'b')
x = "".join(list)
print (x)
0
That's my try
- 2
Laugh as loud as you want
LOL LOL LOL LOL LOL LOL