0

I have a concatenated string, joined by a comma. I need to split this list into a list, but the type of the list must strictly by integers.

doc[column] = map(int, [v for v in value.split(',') if v and len(v)])

ValueError: invalid literal for int() with base 10: ''

I thought adding if v and then perhaps len(v) would resolve the problem. How should I do this?

1
  • change if v and len(v) to if v.strip() Dec 8, 2014 at 12:26

2 Answers 2

5

You need to check the strings are digit-only. You can use str.isdigit:

doc[column] = [int(v) for v in value.split(',') if v.strip().isdigit()]

NOTE: Above will not accept negative integer. To handle it, you need more conditions.

UPDATE

updated the answer to handle ' 1' case:

>>> int(' 1')
1
>>> ' 1'.isdigit()
False
>>> ' 1'.strip().isdigit()
True

UPDATE according to OP's comment:

To be complete, you need to try float/int to see whether the value is convertable to the type.

Example:

def try_float(x):
    try:
        float(x)
        return True
    except (TypeError, ValueError):
        return False

value = '1, 2.3, 4, 5, blah, 6.78'
numbers = [float(x) for x in value.split(',') if try_float(x)]
3
  • @behzad.nouri, Thank you for pointing that. I updated the answer to use str.strip to handle that case.
    – falsetru
    Dec 8, 2014 at 12:30
  • Thanks, I thought isdigit is for char only, my bad. I need to do this as well for floats, but I realized isdigit won't work then. Any clue to handle that case? Dec 8, 2014 at 12:32
  • @Tjorriemorrie, How about this? ideone.com/n7JnXo (Try float and catch exception in a custom function)
    – falsetru
    Dec 8, 2014 at 12:36
1

Make a nicely named function:

def converts_to_int(value):
    try:
        int(value)
        return True
    except ValueError:
        return False

It's shorter to use a list comprehension than use map:

doc[column] = [int(v) for v in value.split(',') if converts_to_int(v)]
2
  • Thanks, but isdigit works fine for integers. I noticed however I'll need to do this for floats. Dec 8, 2014 at 13:04
  • @Tjorriemorrie isdigit works fine if you remove spaces, and your integers are positive.
    – Peter Wood
    Dec 8, 2014 at 14:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.