在Python中高效地將字串重複到特定長度的方法是什麼?


在Python中,一種高效地將字串重複到特定長度的方法是使用字串乘法運算子(*)和字串連線。以下是一些帶有逐步說明的程式碼示例

使用字串乘法運算子

示例

定義原始字串和要重複到的所需長度。

透過使用整數除法 (//) 將所需長度除以字串長度來計算需要重複字串的次數。

使用字串乘法運算子 (*) 將字串乘以計算出的重複次數。

透過切片原始字串(從開頭到所需長度除以原始字串長度的餘數 (%))將任何剩餘字元新增到重複字串的末尾。

string = "foobar"
desired_length = 10
repeated_string = string * (desired_length // len(string)) + string[:desired_length % len(string)]
print(repeated_string)

輸出

foobarfoob

使用while迴圈

示例

定義原始字串和要重複到的所需長度。

建立一個空字串變數來儲存重複的字串。

使用while迴圈將原始字串追加到重複字串變數,直到其長度等於或大於所需長度。

切片重複字串以刪除超過所需長度的任何額外字元。

string = "lorem"
desired_length = 10

repeated_string = ""

while len(repeated_string) < desired_length:
    repeated_string += string

repeated_string = repeated_string[:desired_length]

print(repeated_string)

輸出

loremlorem

使用取模運算和join函式

示例

定義原始字串和要重複到的所需長度。

建立一個列表推導式,使用取模運算子 (%) 來重複原始字串的字元,當到達字串末尾時迴圈回到字串的開頭。

使用join()函式將列表中的字元組合成單個字串。

將生成的字串賦給repeated_string變數。

string = "ipsum"
desired_length = 10

repeated_string = "".join([string[i % len(string)] for i in range(desired_length)])

print(repeated_string)

輸出

ipsumipsum

以下是一些更詳細的程式碼示例,說明如何在Python中高效地將字串重複到特定長度

使用itertools.cycle

示例

匯入itertools模組,該模組提供一個cycle()函式,可以無限重複迭代器。

定義原始字串和要重複到的所需長度。

使用itertools.cycle()建立一個無限重複原始字串的迭代器。

使用itertools.islice()將迭代器的長度限制為所需長度。

使用"".join()將切片的迭代器轉換為字串。

將生成的字串賦給repeated_string變數。

import itertools
string = "Fooqux"
desired_length = 10
repeated_string = "".join(itertools.islice(itertools.cycle(string), desired_length))
print(repeated_string)

輸出

FooquxFooq

使用字串格式化

示例

定義原始字串和要重複到的所需長度。

使用字串乘法 (*) 將原始字串重複必要的次數,以超過所需長度,加一。

使用字串切片 ([:]) 將重複的字串修剪到所需長度。

使用字串格式化將修剪後的字串左對齊 (<) 到所需長度的欄位 ({}).

將生成的字串賦給repeated_string變數。

string = "Sayonara"
desired_length = 12
repeated_string = "{:<{}}".format((string * (desired_length // len(string) + 1))[:desired_length], desired_length)
print(repeated_string)

輸出

SayonaraSayo

使用遞迴

示例

定義原始字串和要重複到的所需長度。

定義一個函式repeat_string(),它接受兩個引數:字串s和所需長度n。

如果字串s的長度大於或等於所需長度n,則返回s最多到n的切片。

否則,使用s與自身連線作為新的字串引數和n作為相同的所需長度引數遞迴呼叫repeat_string()。

將函式呼叫的結果賦給repeated_string變數。

列印repeated_string變數以顯示結果字串。

string = "Senorita"
desired_length = 15
def repeat_string(s, n):
    if len(s) >= n:
        return s[:n]
    else:
        return repeat_string(s + s, n)

repeated_string = repeat_string(string, desired_length)

print(repeated_string)

輸出

SenoritaSenorit

更新於:2023年8月11日

861 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.