Home > Software engineering >  Convert a string to a list of characters in Python (every value of list should be in 2 characters )
Convert a string to a list of characters in Python (every value of list should be in 2 characters )

Time:01-23

Input = '12345678' output = ['12','34','56','78']

I have to convert this Input string to output List as given above. please help to resolve this problem.

list1 = []
list1[0:2] = Input
print("list1..!", list1)
list2 = []

CodePudding user response:

You could use re.findall for a regex option:

import re

inp = '12345678'
output = re.findall(r'\d{2}', inp)
print(output)  # ['12', '34', '56', '78'] 

CodePudding user response:

With simple slicing:

w = '12345678'
res = [w[i:i   2] for i in range(0, len(w), 2)]

['12', '34', '56', '78']

CodePudding user response:

An easier solution as you seem you are a beginner with python is;

input  = '12345678'

str1 = ''
output = []
for i in input:
    if len(str1) > 1:
        output.append(str1)
        str1 = ''
        str1  = i
    else:
        str1  = i

if len(str1) > 1:
    output.append(str1)

print(output)
  • Related