0

I'm new on python and I need to split a input number into a list with 2 digits elements and I think there should be an easyer way to do that.

My code is like this:

  num = int(input("Número: "))

 list = [int(i) for i in str(num)]

 print(list)

The result is:

Número: 34676585535435678
[3, 4, 6, 7, 6, 5, 8, 5, 5, 3, 5, 4, 3, 5, 6, 7, 8]

But I need this:

[34, 67, 65, 85, 53, 54, 35, 67, 8]

Any sugestion, please?

  • 2
    Whilst no answer accepted to link this seems to be a duplicate with an answer here: https://stackoverflow.com/q/9475241/6241235 – QHarr Nov 23 '18 at 23:24
  • Seems to be an exact duplicate of: https://stackoverflow.com/q/2888281/4454124 – mnistic Nov 23 '18 at 23:27

2 Answers2

1

Try:

map(int, [x[2*i:2*i + 2] for i in range(int(ceil(len(str(num)) / 2.)))])

For the above example it returns

[34, 67, 65, 85, 53, 54, 35, 67, 8]

This divides the string to pairs of consecutive pairs of digits (except for the last one which may not be part of a pair), then converts them to ints.

Unrelated, it's preferable not to override existing python reserved names (e.g. list) with variables.

andersource
  • 799
  • 3
  • 9
1

You first convert the int into string, then split it before finally converting it back into a list of int.

x = 34676585535435678
y = str(x)
size = 2 # Set how you would like to split the string 

z = [ int(y[i:i+size]) for i in range(0, len(y), size) ]

print(z) # [34, 67, 65, 85, 53, 54, 35, 67, 8]
boonwj
  • 356
  • 1
  • 10