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]
Sign up to request clarification or add additional context in comments.

5 Comments

you don't even have to convert to a list first. mystr is already iterable. So: list(map(int, mystr))
nice, I was about to post an answer with the list comprehension, but with your edit, I'll just upvote your answer instead!
Given @MarcusMüller's comment why do you not correct your answer to list(map(int, mystr))?
@StevenRumbalski Since that would invalidate the comment.
@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.
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 Comments

How is this different from the other answer?
@DavidG: It doesn't include the unnecessary list(mystr) which is a major improvement. The other answer acts as if strings are not iterable.

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.