2

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.

Devligue
  • 413
  • 5
  • 16

5 Answers5

1

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
Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
1
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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
1

You can try this by List Comprehensions:

[0 if type(i) is str else i for i in h]
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
1

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]
1

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]
postelrich
  • 3,274
  • 5
  • 38
  • 65