将字符串分成n个相等的部分,我们需要创建一个函数,该函数接受原始字符串和要将字符串分成的部分数作为输入,并返回结果为n个相等的字符串。如果字符串包含一些无法分配到n个相等部分的额外字符,则将它们添加到最后一个子字符串中。
example 1的中文翻译为:示例 1在下面的示例代码中,我们创建了一个名为divide_string的方法,该方法接受原始字符串和将字符串划分为的部分数作为输入,并返回n个相等的子字符串作为输出。函数divide_string执行以下操作−
通过将原始字符串的长度除以部分数(n),计算每个子字符串的长度。
使用列表推导式将字符串分成n个部分。我们从索引0开始,并以步长part_length(字符串长度/n)移动,直到达到字符串的末尾。
如果有任何额外的剩余字符没有被添加到子字符串中,我们将它们添加到最后一个子字符串部分。
返回相等长度的n个子字符串。
def divide_string(string, parts): # determine the length of each substring part_length = len(string) // parts # divide the string into 'parts' number of substrings substrings = [string[i:i + part_length] for i in range(0, len(string), part_length)] # if there are any leftover characters, add them to the last substring if len(substrings) > parts: substrings[-2] += substrings[-1] substrings.pop() return substringsstring = abcdefghiparts = 3result = divide_string(string, parts)print(result)
输出['abc', 'def', 'ghi']
example 2的中文翻译为:示例 2在下面的示例中,字符串的长度为26,需要将其分成6个等分。因此,每个子字符串的长度为4。但在将字符串分成6个部分后,字符串的2个字符是多余的,它们被添加到最后一个子字符串中,如输出所示。
def divide_string(string, parts): # determine the length of each substring part_length = len(string) // parts # divide the string into 'parts' number of substrings substrings = [string[i:i + part_length] for i in range(0, len(string), part_length)] # if there are any leftover characters, add them to the last substring if len(substrings) > parts: substrings[-2] += substrings[-1] substrings.pop() return substringsstring = welcome to tutorials pointparts = 6result = divide_string(string, parts)print(result)
输出['welc', 'ome ', 'to t', 'utor', 'ials', ' point']
结论在这篇文章中,我们了解了如何使用python的切片功能将字符串分成n个等分。每个子字符串的长度是通过将字符串的长度除以n来计算的,如果在字符串分割后还有剩余的字符,它们将被添加到最后一个子字符串中。这是一种将字符串分成n个等分的有效方法。
以上就是python程序将字符串分成n个等长的部分的详细内容。