Python程序将字符串分成N个等长的部分

2023年 8月 27日 41.3k 0

Python程序将字符串分成N个等长的部分

在Python中,可以使用切片方法将字符串分成N个相等的部分。可以通过指定子字符串的起始和结束索引来提取相等长度的子字符串。在本文中,我们将看到如何使用Python切片方法将字符串分成N个相等的部分。

将字符串分成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 substrings
string = "abcdefghi"
parts = 3

result = 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 substrings
string = "Welcome to tutorials point"
parts = 6

result = divide_string(string, parts)
print(result)

登录后复制

输出

['Welc', 'ome ', 'to t', 'utor', 'ials', ' point']

登录后复制

结论

在这篇文章中,我们了解了如何使用Python的切片功能将字符串分成N个等分。每个子字符串的长度是通过将字符串的长度除以N来计算的,如果在字符串分割后还有剩余的字符,它们将被添加到最后一个子字符串中。这是一种将字符串分成N个等分的有效方法。

以上就是Python程序将字符串分成N个等长的部分的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论