0

I need to take all the values in a list, and replace them with zeroes if they're a string or their actual number if they're an int. the w.replace is how I'll replace the string, but I don't know what to replace 0 with.

def safe_int(list):

list = [w.replace(, "0") for w in list]
list = [int(i) for i in list]

I want to replace "a" with zero and the entirety of "zebra" with zero inside the list_of_strings.

list_of_strings = ["a", "2", "7", "zebra" ]

The end output should be [0, 2, 7, 0]

2
  • list = [0 if isinstance(w, str) else int(w) for w in list_of_strings] ? Commented Sep 27, 2017 at 21:10
  • @scnerd They're all going to be strings, just some will be strings with digit characters. Commented Sep 27, 2017 at 21:17

2 Answers 2

2

you can try to use string_isdigit

list_of_strings = ["a", "2", "7", "zebra" ]
[int(x) if x.isdigit() else 0 for x in list_of_strings]
Sign up to request clarification or add additional context in comments.

1 Comment

0

you could use try / catch to parse ints, for example like this:

def safe_list(input_list):
    # initialize an output list
    output_list = []

    # iterate through input list
    for value in input_list:
        try:
            # try to parse value as int
            parsed = int(value)
        except ValueError:
            # if it fails, append 0 to output list
            output_list.append(0)
        else:
            # if it succeeds, append the parsed value (an int) to
            # the output list.
            # note: this could also be done inside the `try` block,
            # but putting the "non-throwing" statements which follow
            # inside an else block is considered good practice
            output_list.append(parsed)

    return output_list

Comments