My integer input is suppos 2233445, I want to split and put it into an array as 22, 33, 44, 5.And append them to a list. How will I be able to do it?
Asked
Active
Viewed 191 times
-1
-
What is the logic behind that split? For example, what if the input were 122333445? – Scott Hunter Jan 23 '21 at 14:43
-
its simple, that the output should be 2 digits. If the length of the number is odd then the last digit should be placed alone. e.g(12,23,33,44,5) – Mohamed Mahir Jan 23 '21 at 14:46
4 Answers
0
Simply split the string
data="2233445"
split_strings = [] # final list
n = 2 # length of spliting
for index in range(0, len(data), n):
split_strings.append(data[index : index + n])
print(split_strings)

Yash Makan
- 706
- 1
- 5
- 17
-
Can we do the same process if we don't convert or consider the input as string value? – Mohamed Mahir Jan 23 '21 at 14:43
-
0
One way to do it with regex and get result as list
,
import re
result = re.findall('..?','2233445')
print(result)
WORKING DEMO: https://rextester.com/PWV44308

A l w a y s S u n n y
- 36,497
- 8
- 60
- 103
-
Can we do the same process if we don't convert or consider the input as string value? – Mohamed Mahir Jan 23 '21 at 14:42
-
no, for number you need to do it another way. or cast it to string i.e `str(2233445)` – A l w a y s S u n n y Jan 23 '21 at 15:01
0
s = str(2233445)
output = [int(s[i:i+2]) for i in range(0, len(s), 2)]
output
>>> [22, 33, 44, 5]

Epsi95
- 8,832
- 1
- 16
- 34
0
Try this;
number = 2233445
number = str(number)
pairs = [int(number[i: i + 2]) for i in range(0, len(number), 2)]
print(pairs)
[22, 33, 44, 5]

nectarBee
- 401
- 3
- 9
-
The purpose why I asked this question is because I have to print the sum of 2 digits of the input. Like input = 1122334 output = 66 So that I came up with a logic of splitting the integer into every 2 digits and use a while loop to increment a variable with the 2 digit values. I succeed. If there is any alternative logic to reduce the lines of codes I will be glad. the loop I used: – Mohamed Mahir Jan 23 '21 at 14:50
-
The given answer is for the question you asked.. If not, you have to explictly state your question. – nectarBee Jan 23 '21 at 14:58
-
sorry about that. I really intended to know how to split the integers as I asked. – Mohamed Mahir Jan 23 '21 at 15:06