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 ?

blue-sky
  • 49,326
  • 140
  • 393
  • 691
  • Possible duplicate of [How to split string without spaces into list of integers in Python?](https://stackoverflow.com/questions/29409273/how-to-split-string-without-spaces-into-list-of-integers-in-python) – DavidG Nov 09 '17 at 22:02
  • `list(map(int, '011101111111110'))` works. – Steven Rumbalski Nov 09 '17 at 22:03

2 Answers2

6
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]
Daniel
  • 739
  • 8
  • 20
1

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]
Andronnix
  • 19
  • 3