在本教程中,我们将编写一个程序,将给定的字符串分成相等的部分。让我们来看一个例子。
输入值string = 'Nhooo.com' each_part_length = 5
输出结果Nhooo .comX
输入值string = 'Nhooo' each_part_length = 6
输出结果Nhooo. comXXX
我们将使用itertools模块中的zip_longest方法来获得结果。
zip_longest方法将迭代器作为参数。我们还可以传递fillvalue来对字符串进行分区。它将返回包含等号字符的元组列表。
zip_longest在每次迭代返回一个元组,直到力竭给定的时间最长的迭代器。元组包含来自迭代器的给定长度的字符。
示例# importing itertool module
import itertools
# initializing the string and length
string = 'Nhooo'
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]))
输出结果
如果运行上面的代码,则将得到以下结果。Nhooo .comX
示例# importing itertool module
import itertools
# initializing the string and length
string = 'Nhooo'
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]))
输出结果
如果运行上面的代码,则将得到以下结果。Nhooo. comXXX
结论
如果您对本教程有疑问,请在评论部分中提及。