首頁  >  文章  >  後端開發  >  Python程式將字串分成N個等長的部分

Python程式將字串分成N個等長的部分

王林
王林轉載
2023-08-24 18:49:031263瀏覽

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個等長的部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除