How to replace a element in list of list using python3?
txt =[[""],[""],[""]]
for i in txt:
x = i.replace("", "apples")
print(x)
Expected Output:
apples
apples
apples
How to replace a element in list of list using python3?
txt =[[""],[""],[""]]
for i in txt:
x = i.replace("", "apples")
print(x)
Expected Output:
apples
apples
apples
To replace every instance of "" in the sublists of the main list txt, you can use the following list-comprehension:
txt =[[""],[""],[""]]
txt = [[x if not x=="" else 'apples' for x in sublist] for sublist in txt]
which produces:
[['apples'], ['apples'], ['apples']]
The code you have right now cannot work because given the way you loop over txt, i is the sublist and you python list objects do not have a .replace method.
Using list comprehension:
txt =[[""],[""],[""]]
print([[x if x != "" else 'apples' for x in sub] for sub in txt])
OUTPUT:
[['apples'], ['apples'], ['apples']]
To print them separately;
txt = [[x if x != "" else 'apples' for x in sub] for sub in txt]
for sub in txt:
for elem in sub:
print(elem)
OUTPUT:
apples
apples
apples