user5904838
user5904838

Reputation:

How to check if a value inside a list is a string?

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]

Upvotes: 0

Views: 101

Answers (2)

olieidel
olieidel

Reputation: 1555

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

Upvotes: 0

user8060120
user8060120

Reputation:

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]

Upvotes: 2

Related Questions