Home > Back-end >  How to split string with number without spaces in Python, but 2 digits, 3 digits?
How to split string with number without spaces in Python, but 2 digits, 3 digits?

Time:05-17

I have a string with numbers, I can split to individual numbers like

mynum = '123456'.replace(".", "")
[int(i) for i in mynum]
Output:
[1, 2, 3, 4, 5, 6]

I need to split to 2 digits like

[12, 34, 56]

also 3 digits

[123, 456]

CodePudding user response:

One clean approach would use the remainder:

inp = 123456
nums = []
while inp > 0:
     nums.insert(0, inp % 100)
     inp /= 100

print(nums)  # [12, 34, 56]

The above can be easily modified e.g. to use groups of three numbers, instead of two.

CodePudding user response:

For two-digit splitting:

[int(mynum[i])*10 int(mynum[i 1]) for i in range(len(mynum),2)]

For three-digit splitting:

[int(mynum[i])*100 int(mynum[i 1])*10 int(mynum[i 2]) for i in range(0,len(mynum),3)]
  • Related