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 等份。

更新於: 2023-04-17

4K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.