0

I have a list of integer strings to sort. The format is like this:

l= ['17', '23', '35', '79', .....]

I need to convert each numeric string into an integer so that I can sort their numeric value. I have tried the following,

l.sort(key=int)

However, I got

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

I think it is due to the whitespace in between the strings. Is that correct? If so, how do I solve it?

3
  • 2
    Can you please give an example input that causes this issue? Commented Nov 12, 2016 at 7:31
  • See also stackoverflow.com/questions/2508861/… Commented Nov 12, 2016 at 7:45
  • 1
    Weird, i try your code it did works, space should not be an issue, check your input list whether it contain something that is not numeric or empty Commented Nov 12, 2016 at 7:48

1 Answer 1

1

To remove blank strings from a list:

l = filter(str.strip, l)

Then you can sort as you were.

Sign up to request clarification or add additional context in comments.

4 Comments

@cdarke: It directly solves the OP's problem. I think you just haven't thought about how.
@cdarke it's not... Blank strings raise the OP's exception and this answer filters those out...
However if you're going to use filter @John I'd avoid the lambda and use str.strip directly.
@LijieZhou: Great. Please note that you can "accept" an answer by clicking the checkmark on the left if it solved your problem.

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.