0

I have a list with numerical and string values, like this:

vals = ["1", "2", "A"]

I want to replace all sting values in this list with "0". So that the new list is: ["1", "2", "0"].

Why does not this work?

[i for i in vals if str(i).isnumeric() else "0"]

3 Answers 3

2

Your syntax is invalid. While using if and else in list comprehension, they should come before for loop

vals = ["1", "2", "A"]
new=[i if str(i).isnumeric() else '0' for i in vals]
print(new)
Sign up to request clarification or add additional context in comments.

Comments

0

That's a wrong syntax for comprehension, the if else condition should be checked before for if you want to have the values conditionally:

>>> [i if str(i).isnumeric() else "0" for i in vals ]
['1', '2', '0']

But if you want to have only the values that satisfy the condition, then only you can have if after for <item> in <iterator> without the else part, which is similar to filter builtin:

>>> [i for i in vals if str(i).isnumeric()]
['1', '2']

Comments

0

This is not how .isnumeric() is used. Instead, use .isdigit():

[i for i in vals if str(i).isdigit() else "0"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.