I have:
d = [1,'q','3', None, 'temp']
I want to replace None value to 'None' or any string
expected effect:
d = [1,'q','3', 'None', 'temp']
a try replace in string and for loop but I get error:
TypeError: expected a character buffer object
Use a list comprehension to replace None values in a list in Python, e.g. new_list_1 = ['' if i is None else i for i in my_list] . The list comprehension should return a different value, e.g. an empty string or 0 if the list item is None , otherwise it should return the list item.
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.
None is a valid element, but you can treat it like a stub or placeholder. So it counts as an element inside the list even if there is only a None .
Use a simple list comprehension:
['None' if v is None else v for v in d]
Demo:
>>> d = [1,'q','3', None, 'temp'] >>> ['None' if v is None else v for v in d] [1, 'q', '3', 'None', 'temp']
Note the is None
test to match the None
singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With