Devligue
Devligue

Reputation: 433

Find string values in list and replace them

I have a list full of floats, ints and strings mixed in unknown order. I want to find all string values and replace them with 0. Problem is that i dont know what will this string look like except that it will contain 4 characters (hex number).

So for example i will have such a list:

h = [1, 2, 5.3, '00cc', 3.2, '085d']

And I want to replace those strings (in this example '00cc' and '085d') with zeros so that my final list will look like:

h = [1, 2, 5.3, 0, 3.2, 0]

I know the ways to find string or value in list and replace it but not in case when I know only type and length of list element.

Upvotes: 3

Views: 459

Answers (5)

postelrich
postelrich

Reputation: 3496

If I recall correctly, it is best not to use is to check type and should use isinstance instead. I include unicode just in case but you can remove.

[0 if isinstance(i, (str, unicode)) else i for i in h]

Upvotes: 1

childlikeArchivist
childlikeArchivist

Reputation: 66

I would suggest a list comprehension, which can test and replace the string values simply and cleanly in one line. A list comprehension creates a new list by testing every element in the iterable you give it. This one tests the type of each element and replaces elements of type str with 0.

    >>> h = [1, 2, 5.3, '00cc', 3.2, '085d']
    >>> i = [0 if type(element) == str else element for element in h]
    >>> i
    [1, 2, 5.3, 0, 3.2, 0]

Upvotes: 1

Sakib Ahammed
Sakib Ahammed

Reputation: 2480

You can try this by List Comprehensions:

[0 if type(i) is str else i for i in h]

Upvotes: 2

ForceBru
ForceBru

Reputation: 44838

for X in xrange(0,len(h)):
    if isinstance(h[X],str): h[X]=0

Here isinstance checks whether a member of a list is of some type (str aka string in this case). The list is modified in-place and without any copies.

Upvotes: 1

Muhammad Tahir
Muhammad Tahir

Reputation: 5174

You can do:

h = [1, 2, 5.3, '00cc', 3.2, '085d']
for i, x in enumerate(h):
    if type(x) == str:
        h[i]=0

Upvotes: 1

Related Questions