0

Reading Python - converting a string of numbers into a list of int I'm attempting to convert string '011101111111110' to an array of ints : [0,1,1,1,0,1,1,1,1,1,1,1,1,1,0]

Here is my code :

mystr = '011101111111110'
list(map(int, mystr.split('')))

But returns error :

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-9b0dca2f0819> in <module>()
      1 mystr = '011101111111110'
----> 2 list(map(int, mystr.split('')))

ValueError: empty separator

How to split the string that has an empty splitting separator and convert result to an int array ?

2

2 Answers 2

8
list(map(int, list(mystr)))

Should do the job. You can't split on an empty string, but Python supports casting str to list as a built-in. I wouldn't use map for situations like these though, but instead use a list comprehension:

[int(x) for x in mystr]
5
  • 2
    you don't even have to convert to a list first. mystr is already iterable. So: list(map(int, mystr)) Commented Nov 9, 2017 at 22:01
  • nice, I was about to post an answer with the list comprehension, but with your edit, I'll just upvote your answer instead! Commented Nov 9, 2017 at 22:03
  • Given @MarcusMüller's comment why do you not correct your answer to list(map(int, mystr))? Commented Nov 9, 2017 at 22:22
  • @StevenRumbalski Since that would invalidate the comment.
    – Daniel
    Commented Nov 9, 2017 at 22:23
  • @StevenRumbalski That's a concern for meta. The comment is prominent and I prefer not editing my answer now. Feel free to add a new answer.
    – Daniel
    Commented Nov 9, 2017 at 22:27
3

You don't need to split your string as it is already iterable. For instance:

mystr = '011101111111110'
result = list(map(int, mystr))

print(result) # will print [0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
2
  • How is this different from the other answer?
    – DavidG
    Commented Nov 9, 2017 at 22:09
  • 1
    @DavidG: It doesn't include the unnecessary list(mystr) which is a major improvement. The other answer acts as if strings are not iterable. Commented Nov 9, 2017 at 22:12

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