Python 将字符串分成“N”等份
在Python中,可以使用切片方法将字符串分成N等份。可以通过指定子字符串的起始和结束索引使用Python切片方法提取相等长度的子字符串。在本文中,我们将看到如何使用Python切片方法将字符串分成N个等份。
要将字符串分成N个等份,我们需要创建一个函数,该函数接受原始字符串和要将字符串分成的份数作为输入,并返回结果的N个等长字符串。如果字符串包含一些无法分配到N等份的额外字符,则将它们添加到最后一个子字符串中。
示例1
在下面的示例代码中,我们创建了一个名为 divide_string 的方法,该方法接受原始字符串和字符串分为的份数作为输入,并将输出作为N个等长子字符串返回。函数divide_string执行以下操作:
- 通过将原始字符串的长度除以份数(N)来计算每个子字符串的长度。
-
使用列表推导将字符串分成N部分。我们从索引0开始,并以 part_length(length_of_string/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']
示例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个等分的有效方法。