본문 바로가기
프로그래밍 언어/파이썬

[Python] 문자열을 일정 길이로 자르기

by 컴공맨 2021. 3. 14.
seq='f09f9989x'; length=2; [seq[i:i+length] for i in range(0, len(seq), length)]

# 결과
# ['f0', '9f', '99', '89', 'x']
seq='f09f9989x'; length=2; [''.join(x) for x in zip(*[list(seq[z::length]) for z in range(length)])]

# 결과
#['f0', '9f', '99', '89']
seq='f09f9989x'; length=2; map(''.join, zip(*[iter(seq)]*length))

# 결과
# ['f0', '9f', '99', '89']

참고 사이트
 

Split String into n-size pieces « Python recipes « ActiveState Code

The code below takes a string and returns a list containing the n-sized pieces of the string. For example: splitCount('aabbccdd', 2) => ['aa', 'bb', 'cc', 'dd'] This is useful if you know that data is in a certain format. I use it to parse dates that are n

code.activestate.com

 

 

'프로그래밍 언어 > 파이썬' 카테고리의 다른 글

[Python] eval()  (0) 2021.03.28
[Python] 정규표현식 (계속 추가예정)  (0) 2021.03.14
[Python] count()  (0) 2021.03.06
[Python] dict 정렬  (0) 2021.03.06
[Python] N진수 변환  (0) 2021.02.28