Home > Enterprise >  How to perform .replace() function on list, if list contains strings, integers and/or floats?
How to perform .replace() function on list, if list contains strings, integers and/or floats?

Time:10-31

Imagine I have a list as such:

mylist = [None, None, None, None, None, None, None, '#N/A', '#N/A', '#N/A', '#N/A', None, None, None, '#N/A', None, None, None, None, None, None, None, None, None, None, None, None, None, None]

Now I want to replace all #N/A's with None, and am able to do so with the code below:

#Here we have to say *item and* otherwise it will return:
#AttributeError: 'NoneType' object has no attribute 'replace'
[item and item.replace("#N/A", "None") for item in mylist]
#prints
[None, None, None, None, None, None, None, 'None', 'None', 'None', 'None', None, None, None, 'None', None, None, None, None, None, None, None, None, None, None, None, None, None, None]

However, when the list contains integers, I can't perform this operation anymore, and do not know how to elegantly solve this problem?

mylist = ['xxx', None, 'x', 'x', None, 'Pv', 0, 0, 0, 0, 0, 0, 0, 1, '00000001', '#N/A', 'na', 'na', 'na', 'na', 'na', 'na', 'Suc', 171.1, 'na', 'na', 
6, None, 'H(1970)']
[item and item.replace("#N/A", "None") for item in mylist]
#prints
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "<stdin>", line 4, in <listcomp>
**AttributeError: 'int' object has no attribute 'replace'**

For any bonus points, I also can't convert string to None with replace function:

[item and item.replace("#N/A", None) for item in mylist]
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
TypeError: replace() argument 2 must be str, not None

CodePudding user response:

You could try this:

newlist = [None if item == '#N/A' else item for item in mylist]

That will work regardless of the data types contained in your list.

Given:

mylist = [
    "xxx",
    None,
    "x",
    "x",
    None,
    "Pv",
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    1,
    "00000001",
    "#N/A",
    "na",
    "na",
    "na",
    "na",
    "na",
    "na",
    "Suc",
    171.1,
    "na",
    "na",
    6,
    None,
    "H(1970)",
]

The above code produces:

[
    "xxx",
    None,
    "x",
    "x",
    None,
    "Pv",
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    1,
    "00000001",
    None,
    "na",
    "na",
    "na",
    "na",
    "na",
    "na",
    "Suc",
    171.1,
    "na",
    "na",
    6,
    None,
    "H(1970)",
]

(If you intended all those na values to be #N/A then of course they would end up as None in the result.)

  • Related