将字符串分割成相等的部分(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 次浏览

开启你的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.