在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
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP