Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

동일한 부분으로 문자열 분할(Python의 그루퍼)

<시간/>

이 튜토리얼에서는 주어진 문자열을 동일한 부분으로 나누는 프로그램을 작성할 것입니다. 예를 들어 보겠습니다.

입력

string = 'Tutorialspoint' each_part_length = 5

출력

Tutor ialsp ointX

입력

string = 'Tutorialspoint' each_part_length = 6

출력

Tutori alspoi ntXXXX

zip_longest를 사용할 것입니다. itertools의 메소드 결과를 달성하기 위한 모듈입니다.

zip_longest 방법 반복자 사용 인수로. fillvalue도 전달할 수 있습니다. 문자열을 분할하기 위해. 동일한 수의 문자를 포함하는 튜플 목록을 반환합니다.

zip_longest 주어진 시간에서 가장 긴 반복자가 소진될 때까지 각 반복마다 튜플을 반환합니다. 그리고 튜플은 반복자로부터 주어진 길이의 문자를 포함합니다.

# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 5
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

Tutor ialsp ointX

# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 6
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))

출력

위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

Tutori alspoi ntXXXX

결론

튜토리얼에 의문점이 있으면 댓글 섹션에 언급하세요.