본문 바로가기

IT/Python

How to split a string at specific length in python?

Sample Data

 

123123123

 

Result Data

 

['123','123','123']

 

How to do?

Python Version 3.X

 

Method 1 

string = '123123123'
length = 3

result = list(map(''.join, zip(*[iter(string)]*length)))
print(result)
# ['123', '123', '123']

 

Method 2

string = '12312312312'
length = 3

result = [''.join(x) for x in zip(*[list(string[z::length]) for z in range(length)])]
print(result)
# ['123', '123', '123']

 

Method 3

string = '12312312312'
length = 3


result = [string[i:i+length] for i in range(0, len(string), length)]
print(result)
# ['123', '123', '123', '12']

 

Do you have check diffrence of result between Method1,2 and Method3?

When use Method1 and Method2, it return Only 3 lenght element .

On the other hand when use Method3, it return all element that has a length of 3 or less.

 

Done

반응형