-5

I have a string 12345678 and I want to convert it into a list [1,2,3,4,5,6,7,8] in python.

I tried this method : I tried this method

Jayesh Thanki
  • 2,037
  • 2
  • 23
  • 32
  • It seems like the problem in your code is that you are splitting on commas but you didn't enter the numbers like this: `"1,2,3,4"` – G_M Mar 10 '18 at 06:08
  • 2
    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) – xskxzr Mar 10 '18 at 07:07

2 Answers2

3

You can use map:

list(map(int, '12345678'))  # [1, 2, 3, 4, 5, 6, 7, 8]

Or a list comprehension:

[int(x) for x in '12345678']  # [1, 2, 3, 4, 5, 6, 7, 8]
Alex
  • 18,484
  • 8
  • 60
  • 80
0

If you want without loop or map, You can try:

final_=[]
def recursive(string1):
    if not string1:
        return 0
    else:
        final_.append(int(string1[0]))
        return recursive(string1[1:])
recursive('12345678')
print(final_)

output:

[1, 2, 3, 4, 5, 6, 7, 8]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88