將字串分割成相等的部分(Python 中的 grouper)


在本教程中,我們將編寫一個程式來將給定的字串分割成相等的部分。讓我們來看一個例子。

輸入

string = 'Tutorialspoint' each_part_length = 5

輸出

Tutor ialsp ointX

輸入

string = 'Tutorialspoint' each_part_length = 6

輸出

Tutori alspoi ntXXXX

我們將使用**itertools**模組中的**zip_longest**方法來實現結果。

**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

結論

如果您對本教程有任何疑問,請在評論區提出。

更新於:2020年7月11日

304 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告